简体   繁体   中英

PHP basic OOP question

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

class b extends a
{
    public function __construct()
    {
        echo 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM