user2507818
user2507818

Reputation: 3037

php: issue with calling the parent method

<?php
class HTML
{
protected $name;
public $id;
private $with;
protected function basicAttribute()
{
return "name='$this->name' id='$this->id'";
}
}
Class HTML_div extends HTML
{
public function __construct($id , $name)
{
$this->id = $id;
$this->name = $name;
}
public function getDiv($content)
{
$basicAttribute = $this->basicAttribute();
echo "<div $basicAttribute >$content</div>";
}
}
$objDiv = new HTML_div("bloc_main" , 'avc');
$objDiv->getDiv('this is and example of inheritance in php');

Question:

If I change $basicAttribute = $this->basicAttribute(); to $basicAttribute = parent::basicAttribute();, It also works. So I wonder what is the difference between them? and which is the better way to call parent method?

Upvotes: 0

Views: 82

Answers (2)

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13263

It is quite simple, really. When you extend a class, the new class inherits all the attributes and methods from that class (with the exception of properties and methods that are private). The class that is extended is called the parent class, and the class that is extending is called the child class.

So, if we have a class that looks something like this:

HTML
    basicAttribute()

and we extend it:

HTML_div extends HTML
    basicAttribute() // This method is automatically inherited from HTML
                     // which means that you do not have to create it yourself

So, when you call parent::basicAttribute() from HTML_div you are really calling HTML's method.

I believe this example should explain it in a way that is easy to understand:

class A {
    function test() {
        echo 'A';
    }
}
class B extends A {
    function test() {
        echo 'B';
    }
    function parentTest() {
        parent::test();
    }
}
$b = new B;
$b->test(); // 'B'
$b->parentTest(); // 'A'

Upvotes: 0

ChicagoRedSox
ChicagoRedSox

Reputation: 638

In this exact circumstance, they do the same thing. However, it's generally better to use $this->basicAttribute(). What each of those calls does is this:

  1. $this->basicAttribute() -- calls child's implementation of basicAttribute() if one exists, otherwise looks to the closest ancestor for an implementation (in this case there is only a parent and child, so it calls the parent)
  2. parent::basicAttribute() -- calls closest ancestor's implementation (in this case again, the parent). This will ignore an implementation of basicAttribute() in the child class, so it is advisable to only use it if you override a parent function and want to explicitly call the parent.

Upvotes: 2

Related Questions