Click here to Skip to main content
15,892,697 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello friends. I am new to PHP. I'm trying inheritance in PHP but I'm not able to understand some concepts. When I am calling print_name method from child class nothing gets printed. Can anyone tell me where I am going wrong?

PHP
class Parent_class
{
    var $first_name="David";
    var $last_name="Hussey";
    
    function __construct()
    {
        echo "Parent class object instantiated" . "</br>";
    }
    
    function print_name($name,$surname)
    {
        $this->first_name=$name;
        $this->last_name=$surname;
        
        echo $this->first_name . " ". $this->last_name . "</br>";    
    }
}
    
class Child_class extends Parent_class
{
    var $x="Roger";
    var $y="Nadal";
    
    function __construct()
    {
        echo "Child class object instantiated" . "</br>";
    }
    
    function call_parent_class_function()
    {
        echo $this->x . " ". $this->last_name . "</br>";
        $this->print_name($x,$y);
    }
}

$obj = new Child_class;
$obj->call_parent_class_function();

$obj1 = new Parent_class;
$obj1->print_name("Virat","Kohli");
Posted
Updated 6-Feb-14 2:07am
v4

1 solution

1. Missing
PHP
<?php

at the beginning and
PHP
?>

at the end
2.
PHP
function call_parent_class_function()
{
    echo $this->x . " ". $this->last_name . "</br>";
    //$this->print_name($x,$y);
    $this->print_name($this->x,$this->y);
}
 
Share this answer
 
v2
Comments
Pritam N. Bohra 6-Feb-14 8:30am    
I already added but in the question i just wrote the main part of the program
Peter Leow 6-Feb-14 8:43am    
Look at the change in number 2. It should work now. Remember to accept this solution.
Pritam N. Bohra 6-Feb-14 10:45am    
That solution worked very well. Thank you. I would like to ask one more question. When the child class object is created, the default constructor is called automatically, which in turn calls the parent class constructor. but i my case only the child class constructor's print statement get printed. It should print parent class constructor's print statement as well. Am I correct?
Peter Leow 6-Feb-14 19:44pm    
Carry out experiment with the following 2 scenario separately and see for yourself:
1. Add parent::__construct(); in the child constructor
2. Comment out the child constructor
Pritam N. Bohra 7-Feb-14 7:20am    
Thank you that worked. I thought it would call the parent class constructor automatically

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900