Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Static Variables

Featured Replies

Having a bit of a hard time figuring this out.

 

function staticTest() 
{
static $a = 0;
echo $a;
$a++;
}


staticTest();
staticTest();
staticTest();

 

If I run this I get 012 on appear, however I can't work out why. I know that static variables hold their value when they're not in execution but why does it ignore the following at the top of the function, how would I change this variable if I wanted to?

 

static $a = 0;

 

Any help to let me get my head around this would be much appreciated :). Also should I create every script I make as an OO script? I've got no problem with OO but I can't see how it would be advantageous when linear scripting works well enough?

Cabbage,

You know that static variables hold their value when they're not in execution. So the piece of code below runs only once - when the function and it's static variable are defined and before the function is ever called.

static $a = 0;

 

If you wanted to change the value of $a within the function you would write this:

$a = 'new value';

 

You are changing the value of $a already within your function with this line:

$a++;

This will just increment $a by 1, of course.

 

Also should I create every script I make as an OO script? I've got no problem with OO but I can't see how it would be advantageous when linear scripting works well enough?

The disadvantage of OO scripts is that scripts written for PHP5 sometimes won't work with PHP4 (e.g. PHP4 doesn't do static variables within classes). But it's really a question of taste, if the linear scripting works well enough then you may as well keep it.

OO scripts are most useful if you are going to be creating some functionality that will be reused for several different applications.

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.