note 99900 modified in keyword.extends by danbrown
| From: | danbrown@php.net | Date: | Tue, 14 Sep 2010 15:33:03 +0000 |
| Subject: | note 99900 modified in keyword.extends by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-172555@lists.php.net to get a copy of this message | ||
One thing I figured out after a long time about extending a parent class that, if the child class
does not have any construct function, it will use its parent's construct.
for example:
<?php
class Main
{
public $a;
public function __construct()
{
echo '::Parent Class initiated::';
$this -> a = 'we are in the parent class';
}
}
class Child extends Main
{
public function getA()
{
return $this -> a;
}
}
$main = new Main();
$main -> child = new Child;
echo $main -> child -> getA();
//Output - ::Parent Class initiated::::Parent Class initiated::we are in the parent class
?>
However, If we have a constructor in the child class as well:
<?php
class Child extends Main
{
public function __construct()
{
}
public function getA()
{
return $this -> a;
}
}
?>
Then :
<?php
$main = new Main();
$main -> child = new Child;
echo $main -> child -> getA();
// Output - ::Parent Class initiated::
?>
Note that the parent variable 'a' is not inherited by the child class if the constructor
from the parent class isnt called.
This behaviour of extension made me waste a lot of my precious time, as I could not understand why
some of my child classes were inheriting parent variables and some were not.
Hope this helps someone..
--was--
One thing I figured out after a long time about extending a parent class that, if the child class
does not have any construct function, it will use its parent's construct.
for example:
class Main
{
public $a;
public function __construct()
{
echo '::Parent Class initiated::';
$this -> a = 'we are in the parent class';
}
}
class Child extends Main
{
public function getA()
{
return $this -> a;
}
}
$main = new Main();
$main -> child = new Child;
echo $main -> child -> getA();
//Output - ::Parent Class initiated::::Parent Class initiated::we are in the parent class
However, If we have a constructor in the child class as well:
class Child extends Main
{
public function __construct()
{
}
public function getA()
{
return $this -> a;
}
}
Then :
$main = new Main();
$main -> child = new Child;
echo $main -> child -> getA();
// Output - ::Parent Class initiated::
Note that the parent variable 'a' is not inherited by the child class if the constructor
from the parent class isnt called.
This behaviour of extension made me waste a lot of my precious time, as I could not understand why
some of my child classes were inheriting parent variables and some were not.
Hope this helps someone..
http://php.net/manual/en/keyword.extends.php