PHP OOP:访问受保护方法时父和$之间的差异

时间:2013-07-13 22:32:46

标签: php oop

从扩展类调用受保护的属性或方法时,父和$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!

1 个答案:

答案 0 :(得分:3)

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

在这种情况下,$ this总是调用扩展版本(来自classB),而父将调用classA中的原始版本

注意例子:

<?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 />