我有这个问题要解决: 我创建了两个类,其中第二个是第一个的扩展,我想在那里 从头等舱设置并获取一个变量,但是......我找不到“正确”的方法 基本上是这样的:
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! protected 变量可以在没有任何函数支持的情况下由扩展类设置。只是去 $this->protVariable = "stuff";
但是您将需要一个可能 protected 函数来设置来自第二个类的 ClassOne 的私有(private)变量。同样,必须在 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 );
}
}
关于php - 从另一个 PHP 类设置 protected 变量的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26535535/