How does the static declaration in a PHP class affect the scope and accessibility of variables?
When a variable is declared as static within a PHP class, it becomes a class variable rather than an instance variable. This means that the variable is shared among all instances of the class and can be accessed without needing an instance of the class. It also affects the scope of the variable, allowing it to be accessed using the scope resolution operator (::) outside of the class definition.
class MyClass {
public static $staticVar = 5;
public function printStaticVar() {
echo self::$staticVar;
}
}
echo MyClass::$staticVar; // Accessing static variable outside the class
$myObj = new MyClass();
$myObj->printStaticVar(); // Accessing static variable within an instance