简体   繁体   English

PHP类-如何使类知道父级值

[英]Php Class - How can I make a Class know parent value

<?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 =/"

?>

How can I make it to print "ok"? 如何使它打印“好”?

I mean, the SecondClass should know what FirstClass set as result, see? 我的意思是,SecondClass应该知道FirstClass设置了什么结果,看吗?

Replace $this->result = 'ok'; 替换$this->result = 'ok'; with self::$result = 'ok'; self::$result = 'ok'; in FirstClass constructor. FirstClass构造函数中。

Btw, the code is terrible. 顺便说一句,代码很糟糕。 You're mixing static and instance variables, and extend classes but don't use benefits extension provides. 您正在混合静态变量和实例变量,并扩展类,但不使用扩展提供的好处。

you need to reference the static as self::$result in the first class. 您需要在第一类中将static引用为self :: $ result。

Below should do what you want... 下面应该做你想要的...

<?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 =/"

?>

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

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