0

I'm wondering: Why would I need to use a static variable? When I initiate a class, that class remembers the value of a variable I declare in that class anyway, right? What does the static part add to that?

For example, what's the difference between

class Hello
{
public $variable;

function increaseByOne()
{
$this->variable++;
}
}

and

class Hello
{
public static $variable;

function increaseByOne()
{
self::$variable++;
}
}

? When I execute either of the functions 10 times, $variable will always be 10, right?

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by cwarn23
0

The difference is that when you have multiple classes, you may access $variable which is in class Hello from another class. It is essentially saying why do you need to use global $variable; in a function when you can input it but this is the oop equivelent for when dealing with objects

static $variable;

. For more information you can read the specific page with talks about this at http://php.net/manual/en/language.oop5.static.php and has a few good examples at the top.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.