user1646111
user1646111

Reputation:

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

Is there any difference between parent and $this when calling protected properties or method from extended class? for example:

<?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(); 
?> 

Output:

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

Upvotes: 1

Views: 233

Answers (1)

Jerzy Zawadzki
Jerzy Zawadzki

Reputation: 1985

Difference is when getProperty is extended in class B.

In this case $this would always call extended version (from classB) and parent would call original one in classA

Note example:

<?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();

Output:

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

Upvotes: 3

Related Questions