0

I need some help with inheritance in php. The code below does not produce any output.

Class Father{

	var $car;
	
	Function inherited(){
	print $this->car;
	}
}

Class Son Extends Father{

	Function __Construct(){
	$this->car='Benz';//I'm assuming here that car is still a property of father.
	}
}

$obj= new Father;
$obj1= new Son;

# I expect it to print Benz here, but it doesn't.
$obj->inherited();
#There is no output.
3
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by Brianbc
0

you created TWO DIFFERENT objects. One is a Father object. The other is a Son object. The Son object:
a. Sets the value of car and ...
b. inherits from the Father

So try: $obj1->inherited(); to see the value of car. Maybe this will clear things up for you:

<?php
Class Father{

	var $car="Toyota";
	
	Function inherited(){
	print $this->car;
	}
}

Class Son Extends Father{

	Function __Construct(){
	$this->car='Benz';//I'm assuming here that car is still a property of father.
	}
}

$obj= new Father;
$obj1= new Son;

# I expect it to print Benz here, but it doesn't.
$obj->inherited();//father object
echo '<br>';
$obj1->inherited();//son object
#There is no output.
?>
0

Hi Brian,

Taking your example:

class Father {}

class Son extends Father {}

You can see that Son inherits/extends from Father. Not Father from Son. Therefore, when you call the inherited function on the Father instance you will not get "Benz" outputted.

However, take the following example:

class Father {

    protected $_car;

    public function __construct($car = 'Mercedez') {
        $this->_car = $car;
    }

    public function drives() {
        echo $this->_car;
    }

}

class Son extends Father {}


$father = new Father;
$firstSon = new Son('Rover');

$father->drives(); // Mercedez
$firstSon->drives(); // Rover

// OR

$secondSon = new Son;
$secondSon->drives(); // Mercedez

Because a make of car wasn't provided when creating a new Son instance, the second son inherited the car from his father. In this case, a mercedez.

Does this make any more sense?

R.

Edited by blocblue: n/a

0

Thanks hielo and robothy(in no specific order). I now get it.

Class Father{

	var $property=array();

	Public Function __construct($property){
	$this->property=explode("|",$property);
	}
	
	Public Function auction(){
	foreach($this->property as $value){
	echo $value;
	}
}}

Class Son extends Father{

	Public Function __construct($property){
	$this->property=explode("|",$property);
	foreach($this->property as $value){
	}
	}
	
	Public function __destruct(){
	echo "Thanks!";
	}
}

$biggerman=new Father("House|\n|wife|\n|benz|\n|mac|<br>");
$biggerman->auction();
$smallerman= new son("Son| |is| |Bankrupt!|<br>");
$smallerman->auction();
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.