初学者的PHP类继承

前端之家收集整理的这篇文章主要介绍了初学者的PHP类继承前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. class User{
  2. public $company_name;
  3. }
  4.  
  5. class Employer extends User{
  6. public $fname;
  7. public $sname;
  8. }

这是我创建的test.PHP.我已经包含了类文件.

  1. $employer = new Employer();
  2. $user = new User();
  3. $employer->company_name = "Company name is ";
  4. echo $user->company_name;

当我打印名称没有任何反应时,请让我知道我的代码有什么问题.

您的Employer类扩展了您的User类,但是当您创建$user和$employer对象时,它们是独立的实体且不相关.

想想你的对象:

  1. $employer = new Employer();
  2. // You now have $employer object with the following properties:
  3. // $employer->company_name;
  4. // $employer->fname;
  5. // $employer->sname;
  6.  
  7. $user = new User();
  8. // You now have $user object with the following properties:
  9. // $user->company_name;
  10.  
  11. $employer->company_name = "Company name is ";
  12. // You now have $employer object with the following properties:
  13. // $employer->company_name = 'Company name is ';
  14. // $employer->fname;
  15. // $employer->sname;
  16.  
  17. echo $user->company_name;
  18. // You currently have $user object with the following properties:
  19. // $user->company_name; /* no value to echo! */

如果要使用继承的属性,它的工作方式更像:

  1. class User{
  2. public $company_name;
  3.  
  4. function PrintCompanyName(){
  5. echo 'My company name is ' . $this->company_name;
  6. }
  7. }
  8.  
  9. class Employer extends User{
  10. public $fname;
  11. public $sname;
  12. }
  13.  
  14. $employer = new Employer();
  15. $employer->company_name = 'Rasta Pasta';
  16. $employer->PrintCompanyName(); //echoes 'My company name is Rasta Pasta.'

猜你在找的PHP相关文章