If you are using a child-class. Remember to call the constructor of the parent class aswell before you start using it. Otherwise you might get different results then you expected. It is stated in this document, but I got confused by the given example. So, here is my example:
<?php
error_reporting(E_ALL);
class test {
var $var;
function test() {
$this->var = 3;
}
}
class testing extends test {
function testing() {
parent::test();
}
function My_test() {
return $this->var;
}
}
$p = new testing();
echo $p->My_test();
// Returns 3
extends : héritage
Souvent, vous aurez besoin d'une classe avec des méthodes et fonctions similaires à une autre classe. En fait, il est bon de définir des classes génériques, qui pourront être réutilisées et adaptées à tous vos projets. Pour faciliter cela, une classe peut être une extension d'une autre classe. La classe dérivée hérite alors de toutes les méthodes et variables de la classe de base (cet héritage a de bien que personne ne meurt pour en profiter), mais peut définir ses propres fonctions et variables, qui s'ajouteront. Une classe ne peut hériter que d'une seule autre classe, et l'héritage multiple n'est pas supporté. Les héritages se font avec le mot clé 'extends'.
<?php
class Panier_nomme extends Panier {
var $owner;
function set_owner ($name) {
$this->owner = $name;
}
}
?>
L'exemple ci-dessus définit la classe Panier_nomme qui possède les mêmes variables que la classe Panier et la variable $owner en plus, ainsi que la fonction set_owner(). Vous créez un panier nominatif de la même manière que précédemment, et vous pouvez alors affecter un nom au panier ou en connaître le nom. Vous pouvez de toutes les façons utiliser les mêmes fonctions que sur un panier classique.
<?php
$ncart = new Panier_nomme; // Création d'un panier nominatif
$ncart->set_owner ("kris"); // Affectation du nom du panier
print $ncart->owner; // Affichage du nom du panier
$ncart->add_item ("10", 1); // (héritage des fonctions de la classe père)
?>
Ceci est également appelé une relation "parent-enfant". Vous créez une classe parent, et utilisez extends pour créer une nouvelle classe basée sur la classe parent : la classe enfant. Vous pouvez toujours utiliser cette nouvelle classe enfant et en créer une nouvelle basée sur cette classe enfant.
Note: Les classes doivent être définies avant d'être utilisées ! Si vous voulez que la classe Named_Cart étende la classe Cart, vous devez d'abord définir la classe Cart. Si vous voulez créer une autre classe appelée Yellow_named_cart, basée sur la classe Named_Cart, vous devez d'abord définir la classe Named_Cart. Pour faire court : l'ordre dans lequel les classes sont définies est important.
extends : héritage
03-Mar-2006 11:54
27-Nov-2005 02:48
Just a note: It is possible to have a class inherit from multiple other classes, but only in a one-at-a-time linear hierarchy.
So this works, and C gets A and B functions:
<?php
class A {
public function af() { print 'a';}
public function bark() {print ' arf!';}
}
class B extends A {
public function bf() { print 'b';}
}
class C extends B {
public function cf() { print 'c';}
public function bark() {print ' ahem...'; parent::bark();}
}
$c = new C;
$c->af(); $c->bf(); $c->cf();
print "<br />";
$c->bark();
/**results:**/
//abc
//ahem... arf!
?>
This does NOT work:
<?php
class A {
public function af() { print 'a';}
public function bark() {print ' arf!';}
}
class B {
public function bf() { print 'b';}
}
class C extends B, A /*illegal*/ {
public function cf() { print 'c';}
public function bark() {print ' ahem...'; parent::bark();}
}
$c = new C;
$c->af(); $c->bf(); $c->cf();
print "<br />";
$c->bark();
//Parse Error
?>
19-Nov-2005 06:43
Here is a simple idea that I use when I need my abstract classes (the inherited classes) implemented before my functional classes.
<?php
$_CLASSES = array_merge (
glob ("classes/*/*.abstract.php"),
glob ("classes/*/*.class.php")
);
foreach ($_CLASSES AS $_CLASS) {
require ($_CLASS);
}
?>
31-Mar-2005 08:11
When declaring a class that relies upon another file ( because it extends the class defined in that file ), you should ALWAYS require_once() that file at the top.
This applies even when planning on looping through and including everything in the folder. Use require_once() in your loop, and at the top of the file that NEEDS the include.
07-Mar-2005 02:19
This may seem obvious, but check this scenario. You have a class folder:
+ class
--classA.php
--classB.php
--classC.php
--mainClass.php
Here... classA, classB, classC all extend the mainClass.
If you try to create a function that automatically includes all of the classes in a folder, normally, they are included alphabetically.
When you try to instantiate classC, for example, you will get an error:
"Cannot inherit from undefined class mainClass"
EVEN IF you instantiate the mainClass before you instantiate all of the other classes.
In other words, make sure your primary class is included before all others.
19-Nov-2004 03:48
Multiple inheritence is often more trouble than it's worth. For example, you have a class foo that inherits from both class bar and class baz. Classes bar and baz both have a fubar() method. When you create a foo object and call its fubar() method, which fubar() method is called: bar's or baz's?
It seems to me that using aggregate to glue one class's methods and data to another object is a bit like Ruby's fixins, but I could be wrong...
[[Editor's note:
The aggregate_* functions have been dropped, as of PHP 5
-S
]]
03-Mar-2004 02:35
It is possible to override a method innherited from a parent class by simply re-defining the method (for those of us who enjoy using abstract classes).
<?php
class A
{
var $foo;
function A()
{
$this->foo = "asdf";
}
function bar()
{
echo $this->foo." : Running in A";
}
}
class B extends A
{
function bar()
{
echo $this->foo." : Running in B";
}
}
$myClass = new B;
$myClass->bar();
?>
04-Jul-2003 05:49
Just a simple example about inheritance:
<?php
class a1{
var $a=10;
function a1($a){
$this->a=$a;
}
}
class a2 extends a1{
var $x=11;
function a2($x,$y){
$this->x=$x;
parent::a1($y); // or a1::a1($y) or $this->a1($y)
}
}
class a3 extends a2{
var $q=999;
}
$x=new a3(99,9);
echo $x->a,"<br>",$x->x,"<br> ",$x->q;
?>
The output will be:
9
99
999
23-Jun-2003 05:58
Just a quick note to make things more clear : while multiple inheritance is not allowed, several levels of single inheritance ARE ALLOWED indeed. Just test this example :
<?php
class A {
var $name='A';
function disp() {
echo $this->name;
}
}
class B extends A {
var $name='B';
}
class C extends B {
var $name='C';
}
$truc = new C() ;
$truc->disp(); // Will output C
?>
This is especially important to keep in mind while building a huge object hierarchy. for example :
+GenericObject
->+ Person
->->Employee
->+Computer
->->+WorkStation
->->-> PPC
->->-> Intel
->->+Server
->->->LDAPServer
->->->IntranetWebServer
.. and so on. Multiple level hierarchy relationship are possible in a tree-like structure (each child has one and only one parent, except for the root object).
10-Jun-2003 10:07
a nice example using extends and multiple classes and constructors.
<?php
class CoreObject {
var $name;
function CoreObject($name){
$this->_constructor($name);
}
function _constructor($name){
$this->name = $name;
}
function show(){
printf("%s::%s\n", $this->get_class(), $this->name);
}
function get_class(){
return get_class($this);
}
}
class Container extends CoreObject{
var $members;
function Container($name){
$this->_constructor($name);
}
function &add(&$ref){
$this->members[] = $ref;
return ($ref);
}
function show(){
parent::show();
foreach($this->members as $item){
$item->show();
}
}
function apply(){
}
}
class Person extends CoreObject{
function Person($name){
$this->_constructor($name);
}
}
class Family extends Container {
var $members;
function Family($name){
$this->_constructor($name);
}
}
echo "<pre>\n";
$family = new Family('my family');
$family->add(new Person('father'));
$family->add(new Person('mother'));
$family->add(new Person('girl'));
$family->add(new Person('boy'));
$family->show();
print_r($family);
?>
27-Sep-2002 10:36
[Editor's note: For an alternative to multiple inheritance, see the dynamic binding via object aggregation in the corresponding section of the manual.]
Multiple Inheritance is not supported but it is easy to emulate it:
<?php
class multipleInheritance
{
function callClass($class_to_call)
{
return new $class_to_call();
}
}
class A
{
function insideA()
{
echo "I'm inside A!<br />";
}
}
class B
{
function insideB()
{
echo "I'm inside B!<br />";
}
}
class C extends multipleInheritance
{
function insideC()
{
$a = parent::callClass('A');
$a->insideA();
$b = parent::callClass('B');
$b->insideB();
}
}
$c = new C();
$c->insideC();
?>
---
This will succesfully echo:
I'm inside A!
I'm inside B!
16-Aug-2002 07:37
This prints out 'ab'. No need to create a new instance of a, therefor both methods still exists with same name.
<?php
class a {
function samename(){
echo 'a';
}
}
class b extends a{
function samename(){
echo 'b';
}
function b(){
a::samename();
b::samename();
}
}
$test_obj = new b();
?>
18-Jul-2002 01:42
Just to clarify something about inheritance. The following code :
<?php
class a
{
function call()
{
$this->toto();
}
function toto()
{
echo('Toto of A');
}
}
class b extends a
{
function toto()
{
echo('Toto of B');
}
}
$b=new b;
$b->call();
?>
...will correctly display "toto of B" (that is, the function declared in the parent is correctly calling the redefined function in the child)
11-Dec-2001 08:31
if the class B that extends class A does not have a constuctor function (i.e. a function named B), then the constructor function of A will be used instead, you don't need to make a constructor in B just to call the constructor of A.
For example:
<?php
class A
{
function A()
{
echo "HEY! I'm A!\n";
}
}
class B extends A
{
}
$b = new B();
?>
produces the output:
HEY! I'm A!
07-Nov-2001 09:08
Just one thing that may seem obvious but not mentionned in this page is that you need to include/require the file containing the parent class or else you'll get an error:
<?php
require(dirname(__FILE__).'/'.'myParent.php');
// ...
myChild extends myParent {
// ...
}
// ...
?>
