如何在PHP中从另一个类设置受保护变量的正确方法

4

我有一个问题需要解决: 我创建了两个类,其中第二个是第一个的扩展,我想从第一个类中设置和获取一个变量,但是…我找不到正确的方法来做到这一点 基本上是这样:

class class_one {

    protected $value;
    private $obj_two;

    public function __construct() {
        $this->obj_two = new class_two;
    }

    public function firstFunction() {

        $this->obj_two->obj_two_function();

        echo $this->value; // returns 'New Value' like set in the class two

    }

}

class class_two extends one {   
    public function obj_two_function() {    
        "class_one"->value = 'New Value';   
    } 
}

我该如何做到这一点?

1个回答

5

除非您正在寻求Uroboros,否则第一类不应初始化第二类!受保护的变量可以由扩展类设置,无需任何函数支持。只需使用 $this->protVariable = "stuff"; 即可。

但是,您需要一个可能受保护的函数来设置第二个类中ClassOne的私有变量。同样,在ClassOne中必须制作一个函数来实际检索其值。

class ClassOne {
    private $privVariable;
    protected $protVariable;

    /**
     */
    function __construct () {

    }

    /**
     * This function is called so that we may set the variable from an extended
     * class
     */
    protected function setPrivVariable ($privVariable) {

        $this->privVariable = $privVariable;

    }

}

在第二个类中,您可以调用parent::setPrivVariable()来使用父函数设置值。
class ClassTwo extends \ClassOne {

    /**
     */
    public function __construct () {

        parent::__construct ();

    }

    /**
     * Set the protected variable
     */
    function setProtVariable () {

        $this->protVariable = "stuff";

    }

    /**
     * see ClassOne::setPrivVariable()
     */
    public function setPrivVariable ($privVariable) {

        parent::setPrivVariable ( $privVariable );

    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接