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

Mat*_*des 4 php variables get class set

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

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';   
    } 
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Bal*_* Th 5

第一类不应初始化第二类,除非你正在寻找《奥罗波若斯》!受保护的变量可以由扩展类设置,无需任何函数支持。去吧$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;

    }

}
Run Code Online (Sandbox Code Playgroud)

在第二个类中,您可以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 );

    }

}
Run Code Online (Sandbox Code Playgroud)