Php类 - 如何使类知道父值

时间:2011-09-07 03:23:25

标签: php class

<?php

class FirstClass{
    public static $second;  
    public static $result = 'not this =/';
    public function __construct(){
        $this->result = 'ok';
        $this->second = new SecondClass();
    }   

    public function show(){
        echo $this->second->value;
    }
}

class SecondClass extends FirstClass{
    public $value;
    public function __construct(){
        $this->value = parent::$result; //Make it get "ok" here
    }
}

$temp = new FirstClass();
$temp->show(); //It will show: "not this =/"

?>

如何打印“ok”?

我的意思是,SecondClass应该知道FirstClass设置的结果,参见?

2 个答案:

答案 0 :(得分:2)

$this->result = 'ok';替换为self::$result = 'ok';构造函数中的FirstClass

是的,代码太可怕了。您正在混合静态和实例变量,并扩展类但不使用福利扩展提供。

答案 1 :(得分:1)

你需要在第一个类中引用static作为self :: $结果。

下面应该做你想要的......

<?php

class FirstClass{
    public static $second;  
    public static $result = 'not this =/';
    public function __construct(){
        self::$result = 'ok';
        $this->second = new SecondClass();
    }   

    public function show(){
        echo $this->second->value;
    }
}

class SecondClass extends FirstClass{
    public $value;
    public function __construct(){
        $this->value = parent::$result; //Make it get "ok" here
    }
}

$temp = new FirstClass();
$temp->show(); //It will show: "not this =/"

?>