1

$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!
4

1 回答 1

3

不同之处在于 getProperty 在 B 类中扩展。

在这种情况下,$this 将始终调用扩展版本(来自 classB),而 parent 将调用 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 />
于 2013-07-13T22:40:30.293 回答