What is the difference between public and private variables in a PHP class?
Public variables in a PHP class can be accessed and modified from outside the class, while private variables can only be accessed and modified from within the class itself. To ensure data encapsulation and maintain the integrity of the class, it is best practice to make variables private and provide public methods (getters and setters) to access and modify them.
class MyClass {
private $privateVar;
public $publicVar;
public function getPrivateVar() {
return $this->privateVar;
}
public function setPrivateVar($value) {
$this->privateVar = $value;
}
}
$obj = new MyClass();
$obj->publicVar = 'This is a public variable';
$obj->setPrivateVar('This is a private variable');
echo $obj->publicVar; // Output: This is a public variable
echo $obj->getPrivateVar(); // Output: This is a private variable