Please review this
https://www.php.net/manual/en/language.variables.scope.php#language.variables.scope.static
https://www.php.net/manual/en/language.oop5.static.php#language.oop5.static.methods
https://www.php.net/manual/en/language.oop5.static.php#language.oop5.static.properties
A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
So in the following example:
function test()
{
$a = 0;
echo $a;
$a++;
}
test(); // OUTPUT: 0
test(); // OUTPUT: 0
test(); // OUTPUT: 0
test(); // OUTPUT: 0
The function test always returns Zero as the $a
variable lose its value.
While in this function:
function test()
{
static $a = 0;
echo $a;
$a++;
}
test(); // OUTPUT: 0
test(); // OUTPUT: 1
test(); // OUTPUT: 2
test(); // OUTPUT: 3
Because the $a
variable is static, so it retain its value.
Also in array,
function test()
{
static $lang = array(
'message' => 'Welcome ',
'admin' => 'administrator'
);
var_dump($lang);
$lang['message'] = 'Hello ';
}
test(); // OUTPUT: array(2) { ["message"]=> string(6) "Welcome" ["admin"]=> string(9) "administrator" }
test(); // OUTPUT: array(2) { ["message"]=> string(6) "Hello" ["admin"]=> string(9) "administrator" }
In the previous example, the first run will output "Welcome administartor", while the second run will output "Hello administrator".
Also,
Static variables can be assigned values which are the result of constant expressions, but dynamic expressions, such as function calls, will cause a parse error.
so the following example will cause error
$name = "Omar";
static $lang = array(
'message' => 'Welcome ',
'admin' => 'administrator' . $name,
);
var_dump($lang); // Fatal error: Constant expression contains invalid operations
While the following code is valid one:
$name = "Omar";
$lang = array(
'message' => 'Welcome ',
'admin' => 'administrator' . $name,
);
var_dump($lang); // OUTPUT: array(2) { ["message"]=> string(9) "Welcome " ["admin"]=> string(12) "administratorOmar" }
Also note this:
Static properties are accessed using the Scope Resolution Operator (::) and cannot be accessed through the object operator (->).
It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self, parent and static).
So the following example is valid
class Foo
{
static $lang = array(
'message' => 'Welcome ',
'admin' => 'administrator'
);
}
var_dump(Foo::$lang); // array(2) { ["message"]=> string(9) "Welcome " ["admin"]=> string(9) "administrator" }
While the following example will throw fatal error
class Foo
{
public $lang = array(
'message' => 'Welcome ',
'admin' => 'administrator'
);
}
var_dump(Foo::$lang); // Fatal error: Uncaught Error: Access to undeclared static property Foo::$lang