doupuzhimuhan9216 2014-11-22 11:53
浏览 93
已采纳

PHP:&$这意味着什么?

As I was revieweing PHP sources to find the deprecated call-time-references, I found following 2 things in 3rd party code:

#1
$x = array(&$this, $a, $b);

#2
&$this->foo();

I know that & is meant for marking references. But it makes no sense to me.

In re. #1: When I use array($this) , won't there be a reference saved in the array, too?

In re. #2: When I call foo() of my own instance, why do I need to use $this as reference?

  • 写回答

4条回答 默认 最新

  • douzhechi2435 2014-11-22 11:59
    关注

    I suppose the code came from PHP4 time.

    re #1 - In PHP 4 using array($this) means the same as array(clone($this)) in PHP 5. that is you get a copy of an object instead. In most cases you would like to get the same object though, not its copy. So I suppose the original author used array(&$this) exactly for that reason.

    re #2 is explained in Returning References chapter of the manual

    in this case it it doesn't matter if it's &$this or some &$obj. The reference in fact is applied to the value returned from foo(). This might make sense for example if foo() has some big static $cache object inside and returns part of it back. E.g.

    class MyClass {
      function &foo($id){
        static $cache;
        if (!isset($cache[$id])) {
          $cache[$id] = extract_some_object_from_database($id);
        }
        return $cache[$id];
      }
    }
    

    Notice the "&foo"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度