Accessing Parent Class' property from child

后端 未结 2 1515
遥遥无期
遥遥无期 2021-01-08 00:46

See the following example (PHP)

class Parent
{ 
  protected $_property;
  protected $_anotherP;

  public function __construct($var)
  {
    $this->_prope         


        
2条回答
  •  执笔经年
    2021-01-08 01:33

    This may save you a few hours of searching around.

    Remember: Your Child class only inherits the properties DEFINED in the Parent class... So if you instantiate an object using Parent class and then populate it with data, then this data will NOT be available in your child class...

    It's super obvious of course, but I'm guessing others may run into the same issue.

    A super simple solution is not to extend anything, simply pass the $object of your parent class into your child class through a constructor. This way you have access to all the properties and methods of the object generated by parent class

    Example

    class child {
    
        public parentObject;
    
        public function __construct($parentObject) {
            $this->parentObject = $parentObject;
        }
    
    }
    

    If your $parentObject has a public property $name, then you can access it inside the child class with a function like:

    public function print_name() {
        echo $this->parentObject->name;
    }
    

提交回复
热议问题