如何从最初在超类中声明的类中获取变量?

时间:2014-09-25 15:12:08

标签: php oop

我有两个类,每个类都在不同的文件中。 我尝试从 Class First 访问 Class Second 中最初定义的变量$this->_myvalue,但没有成功,错误消息在不在时使用$ this对象上下文 有人可以告诉我怎么没能从Class Second获得$this->_value

//File First.php
Class First extends Second{

     function some_function(){
         new Second($this->_myvalue); //Using $this when not in object context
     }
}

//File Second.php
Class Second extends Third{
     public $myvalue;
     public function __construct($myvalue = null) {
        $this->_myvalue = $myvalue;
     }
}

1 个答案:

答案 0 :(得分:1)

看起来你误解了继承:

class Parent
{
    public $val;

    public function __construct($val = null) {
        $this->val = $val;
    }
}

class Child extends Parent
{
    public function something() {
        echo $this->val;
    }
}

您现在可以

$parent = new Parent(5);
echo $parent->val; // 5

$child = new Child(10); // __construct is inherited from Parent
echo $child->val; // 10 - public $val is also inherited
$child->something(); // 10