开发者

PHP basic OOP question

class a
{
    public function __construct()
    {
        $this->id = 123;
    }
}

class b extends a
{
    public function __construct()
    {
        ech开发者_JAVA百科o parent::id;
    }
}

How do I pass variables that are set in the first class $this to the second class?


The correct way is to simply use $this->id in your subclass. All public/protected variables are available to subclasses this way. By assigning $this->id without declaring it, you've implicitly made it public. Generally you should explicitly declare the variable in the base class to document your intent to make it public:

class a
{
    public $id;

    public function __construct()
    {
        $this->id = 123;
    }
}

Just remember to call parent::__construct() before you attempt to access members set by the parent class. Unlike some languages (C++) the parent class's constructor will not be automatically invoked for you.

class b extends a
{
    public function __construct()
    {
        parent::__construct();
        echo $this->id;
    }
}


You can use parent::__construct() to get things that are initialized in the parent class. If you don't have anything to initialize in the child class you can avoid __construct() in the child class and it will automatically take the parent construct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜