What is the difference between static and non-static declaration of variables in PHP classes?
Static variables in PHP classes are shared among all instances of that class, while non-static variables are unique to each instance. When declaring a variable as static in a class, it means that the variable belongs to the class itself, not to any specific instance of the class. Non-static variables are specific to each object created from the class.
<?php
class MyClass {
public static $staticVar = 0;
public $nonStaticVar = 0;
public function incrementStaticVar() {
self::$staticVar++;
}
public function incrementNonStaticVar() {
$this->nonStaticVar++;
}
}
$obj1 = new MyClass();
$obj2 = new MyClass();
$obj1->incrementStaticVar();
$obj1->incrementNonStaticVar();
$obj2->incrementStaticVar();
$obj2->incrementNonStaticVar();
echo MyClass::$staticVar; // Output: 2
echo $obj1->nonStaticVar; // Output: 1
echo $obj2->nonStaticVar; // Output: 1
?>
Keywords
Related Questions
- In PHP, what considerations should be taken into account when specifying file paths dynamically, such as in the case of opening files from different directories?
- How can you ensure compatibility with different tabulator characters when working with PHP files?
- What are the potential issues when using fopen to open a file from a URL in PHP?