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


The right way to set a protected variable from another class PHP

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

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';   
    } 
}

我该怎么做?

第一个类不应该初始化第二个类,除非您正在寻找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 );
    }
}