这是我的班级:
class Network {
protected $value = null;
protected $properties = array();
public $type = null;
function __construct($value = null, $type = null) {
$this->value = $value;
$this->type = $type;
}
public function __set($name, $value) {
if(isset($this->{$name})) {
$this->{$name} = $value;
} else {
$this->properties[$name] = new self($value, null);
}
}
public function __get($name) {
return $this->properties[$name]->value;
}
public function __toString() {
return $this->value;
}
}
这就是我要做的事情:
$networks = new \stdClass();
$networks->test= new \Orange_Post\Network('Test');
$networks->test->enabled = true;
$networks->test->enabled->type = 'boolean';
但是我收到错误:
警告:尝试在最后一行分配非对象的属性,$ networks-> test-> enabled-> type ='boolean';
这是我第一次尝试分支并做这样的事情,而我却无法弄清楚我做错了什么。
答案 0 :(得分:4)
那么这里发生了什么?
-A -- first name is taken as an array
-E -- input read is echoed
-d -- specify delimiter to terminate input instead of newline
-e -- input read is echoed and not assigned
-k -- specify number of characters to read
-q -- read y or n character from terminal
-r -- raw mode
-s -- suppress terminal echoing
-t -- test if input is available before reading
-u -- specify file descriptor to read from
-z -- read entry from editor buffer stack
首先,当您尝试将$networks = new \stdClass();
$networks->test= new \Orange_Post\Network('Test');
$networks->test->enabled = true;
$networks->test->enabled->type = 'boolean';
↑ ↑ ↑ ↑ Tries to access a property of a value ('TRUE')
| | | 'enabled' as property never exists
| | Is a property with an instance of '\Orange_Post\Network'
| Is an instance of '\stdClass'
分配给属性true
时。然后调用enabled
,因为该属性不存在。
__set()
在该魔术方法中,您将类本身的新实例分配给属性数组public function __set($name, $value) {
if(isset($this->{$name})) {
$this->{$name} = $value;
} else {
$this->properties[$name] = new self($value, null);
}
}
,并使用名称(properties
)作为索引。
enabled
在此之后,您尝试将属性$networks->test->enabled->type = 'boolean';
设置为属性type
。这里enabled
被调用。
__get
现在您只需返回public function __get($name) {
return $this->properties[$name]->value;
}
的数组值并返回其属性properties
。属性value
不是对象。只需删除value
部分,您的代码就会返回该对象。
换句话说,你的最后一行:
->value
变为:
$networks->test->enabled->type = 'boolean';
答案 1 :(得分:1)
您正在为enabled
属性分配值true
,但下一行是尝试将该属性视为对象(它不是,它是一个布尔值) )。如果您确实需要为enabled
属性设置值和类型,请尝试改为:
$networks->test->enabled = new \stdClass();
$networks->test->enabled->value = true;
$networks->test->enabled->type = 'boolean';
希望这有帮助!