What is the difference between accessing a parent class variable in PHP OOP using protected vs public?
When accessing a parent class variable in PHP OOP, using `protected` allows the variable to be accessed by child classes, while using `public` makes the variable accessible even outside the class hierarchy. If you want the variable to be accessible only to child classes, use `protected`. If you want the variable to be accessible outside the class hierarchy, use `public`.
class ParentClass {
protected $protectedVar = 'I am a protected variable';
public $publicVar = 'I am a public variable';
}
class ChildClass extends ParentClass {
public function getProtectedVar() {
return $this->protectedVar;
}
public function getPublicVar() {
return $this->publicVar;
}
}
$child = new ChildClass();
echo $child->getProtectedVar(); // Output: I am a protected variable
echo $child->getPublicVar(); // Output: I am a public variable