class A{ public function run() { $this->say(); }}class B extends A{ protected function say() { echo 'B-say'; }}$b = new B();$b->run();//结果 输出B-say
If you change say to private, you can't.
Error PHP Fatal Error:call to Private Method B::say () from context ' A '
A private method that means that a cannot access B. Then why protected, protected should not also not be able to do? A is the parent of B is not a subclass.
Reply content:
class A{ public function run() { $this->say(); }}class B extends A{ protected function say() { echo 'B-say'; }}$b = new B();$b->run();//结果 输出B-say
If you change say to private, you can't.
Error PHP Fatal Error:call to Private Method B::say () from context ' A '
A private method that means that a cannot access B. Then why protected, protected should not also not be able to do? A is the parent of B is not a subclass.
Find out where the problem lies. The parent class can access the subclass protected protected method
This represents the object itself. Because b inherits A, B also has all the methods and properties of a. The code doesn't turn out like this.
class B extends A{ protected function say() { echo 'B-say'; } public function run() { $this->say(); }}
The result of such execution is certainly b-say;
If the modifier of the Say method is private, it is not possible to call the say method externally, so it will be an error.
Access modifiers
Private can only be accessed in this class and is not accessible between inheriting classes
Protected inheritable classes are accessible between classes and are not accessible outside the class
That's the difference between private and protect.
Think it is very interesting, analyzed a bit, look here:
Http://www.chengxiaobai.cn/PHP/the-parent-class-calls-the-sub-class-method-in-php.html