0

好吧,我很沮丧,因为我认为我已经解决了这个问题,或者之前已经成功地完成了这个。

快速初步:

  • 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;
}
4

3 回答 3

1
 echo $myRequest->params['baz'];

函数中的 isset 检查将从数组中__get查找并返回。您收到的通知来自类外部以及返回数组中的一个键 - 在您的示例中从未实际定义过该键。"params"$this->_data"baz"

于 2011-06-09T04:19:04.887 回答
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){
        if (array_key_exists($key, $this->_data)) {
            return &$this->_data[$key]; // Note the reference operator
        } else {
            $value = null; // First assign null to a variable
            return $value; // Then return a reference to the variable
        }
    }
}

$this->_data[$key]是一个返回值的操作,所以返回值会导致错误,因为它不是引用。要使其返回引用,您必须使用引用:&$this->_data[$key]

于 2013-05-03T17:32:40.490 回答
0

没有尝试过,因为我避免使用__getand __set,但也许这对你有用:

public function __get($key){
   if(!isset($this->_data[$key]))
       return false;

   return $this->_data[$key];    
}

完全未经测试,但看起来它可能可以完成这项工作。

于 2011-06-09T04:19:12.823 回答