简体   繁体   English

无法从子类访问父变量

[英]Unable to access a parent variables from child class

I want to reuse a few values from the parent class in the child class, but it seems that the child class cannot read the values that use the context $this in the parent method. 我想重用子类中父类的一些值,但是子类似乎无法读取在父方法中使用上下文$this的值。

class Mother{

   public function __construct($field,$val){

       $this->field = $field;

       $this->val = $val;

   }

   public function set(){

        return array('val'=>$this->val,
                    'field'=>$this->field,
                    'test'=>"test");
   }

}

class Sister extends Mother{

   public function getVal(){

     $val = parent::set();

     print_r($val);

   }
}

The output would be 输出将是

  Array ( [val] => [field] => [test] => test)

I have tried to turn the set() method static but that don't have anything to do with the problem. 我试图将set()方法set()静态,但这与问题无关。 Can anyone tell me how to store the values in the parent class and pass it to the child class? 谁能告诉我如何将值存储在父类中并将其传递给子类?

Your example will not print anything, because you don't call the class. 您的示例不会打印任何内容,因为您不会调用该类。

Try this 尝试这个

class Mother{

   public function __construct($field,$val){

       $this->field = $field;

       $this->val = $val;

   }

   public function set(){

        return array('val'=>$this->val,
                    'field'=>$this->field,
                    'test'=>"test");
   }

}

class Sister extends Mother{

   public function getVal(){

     $val = parent::set();

     return $val;

   }
}

$class = new Sister('test1', 'test2');

print_r($class->getVal());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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