I have a construction like this in my config file:
<?php
if (true) {
$nonstatic = 1;
static $config = 1;
}
else {
$nonstatic = 2;
static $config = 2;
}
echo $nonstatic;
echo $config;
?>
So why the $config contains 2 if this part of the statement is false and $nonstatic contains 1? Is it a bug?
The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.
Introduction: A static class in PHP is a type of class which is instantiated only once in a program. It must contain a static member (variable) or a static member function (method) or both. The variables and methods are accessed without the creation of an object, using the scope resolution operator(::).
self is used to access static or class variables or methods and this is used to access non-static or object variables or methods. So use self when there is a need to access something which belongs to a class and use $this when there is a need to access a property belonging to the object of the class.
A static private method provides a way to hide static code from outside the class. This can be useful if several different methods (static or not) need to use it, i.e. code-reuse.
I suppose this chunk is being included from a function.
Initialisations of static variables are resolved at compile-time, and if the interpreter finds multiple initialisations, it simply takes the bottom one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With