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条)

报告相同问题?

悬赏问题

  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式