How can static variables be properly utilized in PHP classes to avoid overwriting them with each new instance?
When using static variables in PHP classes, they are shared across all instances of the class, which can lead to unintended overwriting of their values. To avoid this, you can use the static keyword to declare the variable within the class scope, ensuring it is only initialized once and retains its value across all instances.
class MyClass {
private static $staticVar;
public function setStaticVar($value) {
self::$staticVar = $value;
}
public function getStaticVar() {
return self::$staticVar;
}
}
$instance1 = new MyClass();
$instance2 = new MyClass();
$instance1->setStaticVar('Hello');
echo $instance2->getStaticVar(); // Output: Hello