Home » Php » PHP Class Inheritance for Beginners

PHP Class Inheritance for Beginners

Posted by: admin July 12, 2020 Leave a comment

Questions:
class User{
    public $company_name;
}

class Employer extends User{
    public $fname;
    public $sname;
}

this is the test.php i have created. I have included the class file.

$employer = new Employer();
$user = new User();
$employer->company_name = "Company name is ";
echo $user->company_name;

When i print the name nothing happens, please let me know what is the wrong with my code.

How to&Answers:

Your Employer class extends your User class but when you create your $user and $employer objects they are separate entities and unrelated.

Think of your objects like this:

$employer = new Employer();
// You now have $employer object with the following properties:
// $employer->company_name;
// $employer->fname;
// $employer->sname;

$user = new User();
// You now have $user object with the following properties:
// $user->company_name;

$employer->company_name = "Company name is ";
// You now have $employer object with the following properties:
// $employer->company_name = 'Company name is ';
// $employer->fname;
// $employer->sname;

echo $user->company_name;
// You currently have $user object with the following properties:
// $user->company_name;  /* no value to echo! */

If you want to use inherited properties, it works more like this:

class User{
    public $company_name;

    function PrintCompanyName(){
        echo 'My company name is ' . $this->company_name;
    }
}

class Employer extends User{
    public $fname;
    public $sname;
}

$employer = new Employer();
$employer->company_name = 'Rasta Pasta';
$employer->PrintCompanyName();  //echoes 'My company name is Rasta Pasta.'

Answer:

Don’t confuse your variables, $user and $employer, with classes. $user is an instance of class User, and $employer is an instance of class Employer, but they are separate variables.

Answer:

You never set $user->company_name.

echo $employer->company_name;

Answer:

You didn’t assign something to $company_name of object $user; only to $employer.

Answer:

You just have to echo

 $employer->company_name;

or set

 $user->company_name

to some value.

You do not have to create an instance of the parent class to work with a child class. In this case, the $employer inherits company_name from the User class.