&

编程入门 行业动态 更新时间:2024-10-09 21:19:44
本文介绍了& __ get()问题再次出现.重大挫败感即将到来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

好的,我感到非常沮丧,这是因为我以为自己已经解决了这个问题,或者之前已经成功完成了这项工作.

Alrighty, I'm getting quite frustrated, namely because I thought I had this issue solved, or had accomplished this successfully before.

快速入门:

  • PHP 5.3.6.
  • 错误报告更改为11(实际上是 -1;将来很安全,所有错误/通知)
  • PHP 5.3.6.
  • Error reporting cranked to 11. (-1 actually; future safe, all errors/notices)

我有一个类,它汇总了请求参数.对于傻笑,这里是精简版:

I have a class, it aggregates request parameters. For giggles here is a stripped down version:

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不存在,我总是会出错.我已经尝试过:

Anyways, the reason for arrg! is, no matter what I try, I always get an error whenever the $key doesn't exist. I've tried:

// doesn't work $null = null; if(isset($this->_data[$key])){ return $this->_data[$key]; } return $null; // doesn't work return $this->_data[$key];

有人告诉我三元运算符不能得出一个引用,因此,当然不会起作用,但是我们知道从if条件尝试仍然可以.发生什么情况,例如:

I've been told ternary operators cannot result in a reference, ergo, that of course doesn't work, but we know that from the if condition attempt anyways. What happens, for example:

// 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'];

我在这里迷失了方向;也许我幻想了一个实现这一目标的场景.不可能(不发出通知)成功做到这一点吗?

I'm losing my mind here; perhaps I hallucinated a scenario where I achieved this. Is it not possible to (without throwing a notice) successfully do this?

说明:我尝试过的事情

上述内容:

// 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; }

推荐答案

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

__get函数中的isset检查将从$this->_data查找"params"并返回数组.您得到的通知是从类外部获取的,并且有关返回的数组中的键"baz"-在您的示例中从未真正定义过.

The isset check in your __get function will look up "params" from $this->_data and return the array. The notice you get is from outside the class and about a key "baz" in the returned array - which in your example was never actually defined.

更多推荐

&

本文发布于:2023-10-27 23:53:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534897.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:amp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!