PHP class inheritance for beginners

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

this is the test.php that i created. I have included a 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, let me know what happened to my code.

+6
php class
source share
5 answers

Your Employer class extends your User class, but when you create the $user and $employer objects, they are separate objects and are not related.

Think of your objects as:

 $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 something 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.' 
+14
source share

Do not confuse the $user and $employer variables with the classes. $user is an instance of the User class, and $employer is an instance of the Employer class, but they are separate variables.

+4
source share

You never set $user->company_name .

 echo $employer->company_name; 
+3
source share

You have not assigned something to $company_name of the $ user object; only for the employer.

+3
source share

You just need an echo

  $employer->company_name; 

or install

  $user->company_name 

to a certain value.

You do not need to instantiate the parent class to work with the child class. In this case, employer $ inherits company_name from the User class.

+2
source share

All Articles