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.

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.
?>

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.

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();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.