- class User{
- public $company_name;
- }
- class Employer extends User{
- public $fname;
- public $sname;
- }
- $employer = new Employer();
- $user = new User();
- $employer->company_name = "Company name is ";
- echo $user->company_name;
您的Employer类扩展了您的User类,但是当您创建$user和$employer对象时,它们是独立的实体且不相关.
想想你的对象:
- $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! */
如果要使用继承的属性,它的工作方式更像:
- 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.'