I started to learn OO a few days back, I’m quite OK with procedural coding but obviously that is not enough and I want to become a well versed coder with a lot of experience and knowledge, so first thing to learn completely must be OO followed by the right design patterns I think.
Anyhow, I have one thing where I’m stuck which I don’t quite follow…
Static variables… I understand that a static variable doesn’t lose it’s value even if the containing function is finished executing, and will keep it’s value if the same function is executed again, and again etc etc.
But what I don’t understand is what exactly can you now assign to a static variable? The manual and also countless question on stackoverflow state you can not assign an expression to a static variable.
So I read the PHP manual, to find out exactly what is considered an expression? The manuals answer is (and I quote):
“In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is “anything that has a value”.”
“When you type “$a = 5″, you’re assigning ‘5’ into $a. ‘5’, obviously, has the value 5, or in other words ‘5’ is an expression”
http://php.net/manual/en/language.expressions.php
Now when you read about variable scope in the manual, they have exactly this example:
function test()
{
static $a = 0;
echo $a;
$a++;
}
So, the manual about variable scopes says static $a = 0; is fine, while the manual about expressions says $a = 5, would be an expression. Which is basically the same thing, just a 0 instead of a 5…
So I’m a bit confused now.
What exactly is an expression now and what exactly can I or can I not assign to static variables? 🙂
You cannot initialize a
staticvariable using a non-constant expression. You can assign anything you like to it after it is initialized.The difference is that
staticvariables are initialized during the parsing phase, i.e. while PHP reads through the source code to figure out what’s what. At that stage no code is executed, PHP just reads what you want it to do. Therefore, it will not execute code to initialize the variable.'bar'is a constant value which PHP can easily assign to the variable at parse time.Bar::baz()is an expression that needs to run, PHP needs to locate the class, load it if necessary, run thebaz()method, which may do all sorts of different stuff… The same for5 + 3,md5('bar')or anything that requires actual computation. PHP is simply not going to do all this dynamic stuff at parse time. Therefore you cannot initialize astaticvariable with anything but constant values.At runtime, you can assign anything you like to a
staticvariable. An often used pattern is this:This keeps the instance of
SomeObjectin thestaticvariable, but you cannot initialize the variable with it.