dongxiaoke2018 2011-12-23 21:18
浏览 40
已采纳

为什么代码表现为这种方式WRT引用返回?

This is my setting:
display_startup_errors = on
display_errors = On
error_reporting = E_ALL | E_STRICT

$b;
function func ($name) {
  global $b;
  $b = 10;
  return $b;
  }
$a =& func("myname");
++$a ;
echo '<br/>$a= '.$a.' $b= ' .$b."<br/>";
xdebug_debug_zval('a'); echo "<br/> ";

The above code output's the following notice:

Strict standards: Only variables should be assigned by reference in /path/to/file/file.php on line 'some line number'
$a= 11 $b= 10
a: (refcount=1, is_ref=0)=11

Why is the above code displaying the notice? And why is there a C.O.W (copy on write) taking place?

$b;
function &func ($name) {//change here: to return a reference.
  global $b;
  $b = 10;
  return $b;
  }
$a =& func("myname");
++$a ;
echo '<br/>$a= '.$a.' $b= ' .$b."<br/>";
xdebug_debug_zval('a'); echo "<br/> ";

The above code will output:

$a= 11 $b= 11
a: (refcount=1, is_ref=1)=11

Why is no strict standards notice thrown here? And here the reference works.

$b;
function &func ($name) {
  global $b;
  $b = 10;
  return $b;
  }
$a = func("myname"); //change here: removed &
++$a ;
echo '<br/>$a= '.$a.' $b= ' .$b."<br/>";
xdebug_debug_zval('a'); echo "<br/> ";

The above code will output:

$a= 11 $b= 10
a: (refcount=1, is_ref=0)=11

Why does a C.O.W take place here?

For info on xdebug_debug_zval visit here.

  • 写回答

3条回答 默认 最新

  • doubaoguo7469 2011-12-23 21:55
    关注

    How the hell did I miss this: This completely mutes my question! from Returning References at PHP manual

    Note: If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else. Since PHP 4.4.0 in the PHP 4 branch, and PHP 5.1.0 in the PHP 5 branch, an E_NOTICE error is issued if the code tries to return a dynamic expression or a result of the new operator.

    To use the returned reference, you must use reference assigment:

    <?php
    function &collector() {
      static $collection = array();
      return $collection;
    }
    $collection = &collector();
    $collection[] = 'foo';
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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