I want to call the private attribute of the subclass in the parent class, but a 500 error is reported.
<code>class A { public function __get($name) { $getter = 'get' . $name; if (method_exists($this, $getter)) { return $this->$getter(); } } } class B extends A { private function getname() { return 'karly'; } } $b = new B(); echo $b->name;</code>
After this code is run, the server reports a 500 error. Why does calling method_exists return true, but the method cannot be returned? Thanks.
I want to call the private attribute of the subclass in the parent class, but a 500 error is reported.
<code>class A { public function __get($name) { $getter = 'get' . $name; if (method_exists($this, $getter)) { return $this->$getter(); } } } class B extends A { private function getname() { return 'karly'; } } $b = new B(); echo $b->name;</code>
After this code is run, the server reports a 500 error. Why does calling method_exists return true, but the method cannot be returned? Thanks.
First follow the official php documentation:
public means global and can be accessed by subclasses inside and outside the class;
private means private and can only be used within this class;
protected means protected and can only be accessed in this class or subclass or parent class;
Secondly, the meaning of method_exists is to test whether it exists. The problem is that it really exists, but it just doesn’t have permission. This is not a problem.
In summary, you should use protected
It seems that private member methods can only be called by themselves