inherit Classes - I dont get this:

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
grkpfl
Forum Newbie
Posts: 6
Joined: Fri Sep 16, 2005 3:32 am

inherit Classes - I dont get this:

Post by grkpfl »

Hi!

F.E I have this class:

Code: Select all

class Person{
var $name;
var $age;
var $hairs;

function Person($a, $b, $c){
$this->name = $a;
$this->age = $b;
$this->hairs = $c;
}

function Say(){
echo "Name:".$this->name."<br>Age:".$this->age."<br>Hairs:".$this->hairs;
}
}
and now i want to inherit it like

Code: Select all

class Animal extends Person{
var $color;
}

so how can i change through "Animal" one of "Person" functions ? or is this not possible?
f.e. ass you can see i made a function in "Person" which will store something in "Person's" variables.
how can i extend that for "Animal"?

example:

Code: Select all

$p1 = new Person("Tom", 21, "brown");
$a1 = new Animal("Bonzo", 5, "yellow", "white");???????
or:

Code: Select all

$p1->say(); // Tom 21 brown
$a1->say(); // Bonzo 5 yello, white?????????????
i dont get this

thanks
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post by raghavan20 »

you must have to call within the child constructor

Code: Select all

function Animal($a,$b,$c,$d){
parent::__construct($a,$b,$c); //PHP 5:you have to send any of the three variables that have to the child constructor
//parent::Person($a,$b,$c);//PHP 4:if the above does not work; try this
}
if the child has more than one parent,,i.e multiple inheritance it would dynamically map to the correct parent depending on the parameters provided.

all the methods in the parent are accessible to the child including the member variables.

so calling

Code: Select all

$animalInstance = new Animal();
$animalInstance->say(); //should work
will work

i dont really see a necessity for the inheritance relationship; if you want to use a class you can just use it now really to be a parent class.
grkpfl
Forum Newbie
Posts: 6
Joined: Fri Sep 16, 2005 3:32 am

Post by grkpfl »

ahh, i understand :D
thanks
Post Reply