好吧,我很沮丧,因为我认为我已经解决了这个问题,或者之前已经成功地完成了这个。
快速初步:
- PHP 5.3.6。
- 错误报告增加到 11。(
-1
实际上;未来安全,所有错误/通知)
我有一个类,它聚合请求参数。对于咯咯笑,这里是一个精简版:
class My_Request{
private $_data = array();
public function __construct(Array $params, Array $session){
$this->_data['params'] = $params;
$this->_data['session'] = $session;
}
public function &__get($key){
// arrg!
}
}
无论如何,原因arrg!
是,无论我尝试什么,只要$key
不存在,我总是会收到错误。我试过了:
// doesn't work
$null = null;
if(isset($this->_data[$key])){ return $this->_data[$key]; }
return $null;
// doesn't work
return $this->_data[$key];
有人告诉我,三元运算符不能产生引用,因此,这当然不起作用,但我们if
无论如何都从条件尝试中知道这一点。会发生什么,例如:
// params will have foo => bar, and session hello => world
$myRequest = new My_Request(array('foo' => 'bar'), array('hello' => 'world'));
// throws an error - Undefined index: baz
echo $myRequest->params['baz'];
我在这里发疯了;也许我幻想了一个我实现这一目标的场景。是否不可能(不发出通知)成功地做到这一点?
澄清:我尝试过的事情
之前所提:
// no check, no anything, just try returning : fails
public function &__get($key){
return $this->_data[$key];
}
// null variable to pass back by reference : fails
public function &__get($key){
$null = null;
if(isset($this->_data[$key])){
return $this->_data[$key];
}
return $null;
}
其他尝试:
// can't work - can't return null by reference nor via ternary : fails
public function &__get($key){
return isset($this->_data[$key])
? $this->_data[$key]
: null;
}