PHP OOP:访问受保护的方法时,parent和$this之间的区别


PHP OOP: difference between parent and $this when accessing protected method

从扩展类调用受保护的属性或方法时,父级和$this之间有什么区别吗?例如:

<?php 
class classA  
{  
    public $prop1 = "I'm a class property!";  
    public function setProperty($newval)  
    {  
        $this->prop1 = $newval;  
    }  
    protected function getProperty()  
    {  
        return $this->prop1 . "<br />";  
    }  
}  
class classB extends classA  
{  
    public function callProtected()  
    {  
        return $this->getProperty();  
    } 
    public function callProtected2()  
    {  
        return parent::getProperty();   
    }
}  
$testobj = new classB;  
echo $testobj->callProtected();  
echo $testobj->callProtected2(); 
?> 

输出:

I'm a class property!
I'm a class property!

区别在于在类B中扩展getProperty。

在这种情况下,$this将始终调用扩展版本(来自类B),父级将调用类A 中的原始版本

注意示例:

<?php
class classA
{
    public $prop1 = "I'm a class property!";
    public function setProperty($newval)
    {
        $this->prop1 = $newval;
    }
    protected function getProperty()
    {
        return $this->prop1 . "<br />";
    }
}
class classB extends classA
{
    protected function getProperty() {
        return 'I''m extended<br />';
    }
    public function callProtected()
    {
        return $this->getProperty();
    }
    public function callProtected2()
    {
        return parent::getProperty();
    }
}
$testobj = new classB;
echo $testobj->callProtected();
echo $testobj->callProtected2();

输出:

I'm extended<br />
I'm a class property!<br />