【问题标题】:The right way to set a protected variable from another class PHP从另一个类 PHP 设置受保护变量的正确方法
【发布时间】:2014-10-23 19:08:12
【问题描述】:
我有这个问题要解决:
我创建了两个类,第二个是第一个的扩展,我想在那里
设置并从头等舱获取变量,但是...我找不到“正确”的方法
基本上是这样的:
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';
}
}
我该怎么做?
【问题讨论】:
标签:
php
class
variables
get
set
【解决方案1】:
第一类不应该初始化第二类,除非你正在寻找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 );
}
}