How can public variables in PHP classes be initialized and modified externally through method calls?
To initialize and modify public variables in PHP classes externally through method calls, you can create setter methods within the class. These setter methods can be used to set the values of the public variables from outside the class. By calling these setter methods, you can modify the public variables while maintaining encapsulation and control over the data being set.
class MyClass {
public $publicVar;
public function setPublicVar($value) {
$this->publicVar = $value;
}
}
$obj = new MyClass();
$obj->setPublicVar("New Value");
echo $obj->publicVar; // Output: New Value