【发布时间】:2011-06-09 04:08:15
【问题描述】:
好吧,我很沮丧,因为我认为我已经解决了这个问题,或者之前已经成功地完成了。
快速初步:
- 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];
有人告诉我,三元运算符不能产生引用,ergo,这当然不起作用,但我们从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;
}
【问题讨论】:
标签: php reference getter magic-methods