Reputation: 3037
<?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
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
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:
Upvotes: 2