快速规格:
PHP 5.3
error_reporting(-1) // the highest
我正在使用__get()
引用技巧来神奇地访问对象中任意深度的数组元素。
快速举例:
public function &__get($key){
return isset($this->_data[$key])
? $this->_data[$key]
: null;
}
这不起作用,因为未设置$key
时,它会尝试通过引用返回null
,这当然会抛出 Only variable references should be returned by reference ...
I尝试修改如下:
public function &__get($key){
$null = null;
return isset($this->_data[$key])
? $this->_data[$key]
: $null;
}
但仍然无效,我假设将$null
设置为null
,基本上unset()
。
我该怎么办?谢谢!
刚想我会推广这个问题,因为它有点相关( PHP魔术和参考); __callStatic(), call_user_func_array(), references, and PHP 5.3.1。我还没有找到答案......除了修改PHP核心。
答案 0 :(得分:19)
这与null
无关,而是与三元运算符无关:
使用if/else
重写它不会引发通知:
public function &__get($key)
{
$null = null;
if (isset($this->_data[$key])) {
return $this->_data[$key];
} else {
return $null;
}
}
三元运算符不能产生引用。他们只能返回值。
答案 1 :(得分:4)
为什么要明确返回null
?如果$key
中不存在$this->_data
,那么它会返回NULL
吗?
我建议使用以下内容并在另一端调整逻辑。您现在可能已经在检查null
了。您可以将其更改为empty()
或其他变体。或者使用 Matthieu 建议的例外情况。
public function &__get($key){
return $this->_data[$key];
}
答案 2 :(得分:3)
我有这个问题,但我最终意识到当找不到密钥时我不应该返回null,但是抛出异常(因为我毕竟访问了一个未知属性)
但也许这不是你想要做的,我只是想分享它。