I am have a problem with undestanding some sentence at PHP.net about the static keyword, At This Link , PHP.net Explaining about the static keyword i did understand all they say but i didn't succeed to get one sentence witch start at "Like any other PHP static variable". I just didn't get it if can some one please help me with code example, mabye explanation will be great.
When saying "like any other static variable" the manual refers to a static variable inside a function. The archetypal example is the function that keeps an internal counter:
function foo() {
static $counter = 0; // static variable
return ++$counter;
}
Static variables like this and static class properties both have a limitation on the expressions you can initialize them with.
function foo() {
static $counter = getInitialValue(); // ERROR: not possible!
return ++$counter;
}
If you need to do something like this, the usual workaround is
function foo() {
static $counter; // not initialized explicitly, same as = null
if ($counter === null) { // three equals!
$counter = getInitialValue();
}
return ++$counter;
}
Basically, you can do this:
class Foo
{
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static;
}
}
where $my_static
is initialise as a string with the value foo
. But you can't do:
class Foo
{
public static $my_static = substr('food',0,3);
public function staticValue() {
return self::$my_static;
}
}
and expect $my_static
to contain the results of the function call to substr
; directly assigning a function's return value to a static variable is an illegal operation. Similarly, you can't do:
class Foo
{
public static $my_static = 'foo';
public static $my_static_2 = $my_static;
public function staticValue() {
return self::$my_static;
}
}
because you may not initialise a static variable by pointing to another variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.