本文介绍了PHP子类访问父变量问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上了这堂课:

Class Username {
protected $id;
protected $username;
protected $contact_information;

     private __construct($id) {
       $this->id = (int) $id; // Forces it to be a string
       $contact_information = new ContactInformation($this->id);
     }
}

Class ContactInformation extends Username {
    protected $mobile;
    protected $email;
    protected $nextel_id;
    .....
}

我的问题是:我想在ContactInformation上访问$ id和$ username(以及许多其他变量),但是parent ::或$ this->无法正常工作,每次我执行"new ContactInformation .. ..)PHP创建了一个新用户名",是否有机会从用户名访问CURRENT值?

My problem is: I want to access the $id and $username (and lots of other variables) on ContactInformation, but parent:: or $this-> does NOT work, looks like everytime i do "new ContactInformation....) PHP creates a "new Username". Any chance to access the CURRENT values from Username?

谢谢

推荐答案

为什么Username构造函数是私有的?如果要避免创建用户名,请将该用户名类抽象化.另外,请勿从父类中创建新的联系信息.这是另一种表达方式:

Why is the Username constructor private? If you mean to make it impossible to create a Username, make the Username class abstract. Also, do NOT make a new contact information from the parent class. Here's another way to put it:

abstract class Username {
   protected $id;
   protected $username;

   public __construct($id) {
      $this->id = (int) $id; // Forces it to be a string
   }
}

class ContactInformation extends Username {
    protected $mobile;
    protected $email;
    protected $nextel_id;
    public __construct($id, $mobile, $email, $nextel_id) {
       parent::__construct($id)
       $this->mobile = $mobile;
       ....
    }
}

现在,您可以直接创建一个ContactInformation,而不是直接实例化Username(现在是不可能的).然后,ContactInformation在其自己的构造函数中调用Username构造函数.

Now, instead of instantiating the Username directly (which is now impossible), you instead create a ContactInformation. ContactInformation then calls the Username constructor in its own constructor.

这篇关于PHP子类访问父变量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:30