note 72232 deleted from keyword.extends by colder
| From: | colder@php.net | Date: | Mon, 08 Jan 2007 22:11:33 +0000 |
| Subject: | note 72232 deleted from keyword.extends by colder | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-121464@lists.php.net to get a copy of this message | ||
Note Submitter: Tim Maynard
Reason: useless
----
multiple inheritance has been a constant concern for me (and several others) and i found that if you
declare the class's members and methods as protected, several benefits arise:
- the members and methods are only accessible internally from the current and inherited class's
methods.
- any non-overloaded members and methods of a parent are accessible to the entire depth of children
- overloading of members and methods are normal for any depth of children
+ prevents name clashing because it tells PHP which order to overload identically named members and
methods
<?php
class A {
protected $a = 'im a';
protected function getMe()
{
return $this->a."\n";
}
public function __construct()
{
echo $this->getMe();
}
}
class B extends A {
protected $b = 'im b';
protected function getMe()
{
return $this->b.' ... '.$this->a."\n";
}
public function __construct()
{
echo $this->getMe();
}
}
class C extends B {
protected $c = 'im c';
protected function getMe()
{
return $this->c.' ... '.$this->b.' ... '.$this->a."\n";
}
public function __construct()
{
echo $this->getMe();
}
}
class D extends C {
protected $d = 'im d';
protected function getMe()
{
return $this->d.' ... '.$this->c.' ... '.$this->b.' ...
'.$this->a."\n";
}
public function __construct()
{
echo $this->getMe();
}
}
$mya = new A;
$myb = new B;
$myc = new C;
$myc = new D;
?>
this prints the following w/o error:
im a
im b ... im a
im c ... im b ... im a
im d ... im c ... im b ... im a
in summary, the "protected" declaration keeps whats private private and whats supposed to
be public public and allows similar functionality of multiple inheritance -- though not as easily as
C++'s , (comma) but still present for those in need.