开发者

php reference versus value

  class Test {
      private $arr;
      function __construct() {
          $this->arr = array('test');
      }

      function getArr() {
          return $this->arr;
      }
  }
  $a = new Test();
  $b = $a->getArr();
  $b[0][0] = 'a';
  $s = $a->getArr(); 
  echo $s[0]

Why does this echo test instead of aest? Does PHP copy the array and the contents of the array when returning it? 开发者_JS百科How do I get an array in which I can change the strings and have it reflected in the object?


By returning and assigning by reference:

class Test {
    //...
    function &getArr() {
        return $this->arr;
    }
}
$a = new Test();
$b =& $a->getArr();
$b[0][0] = 'a';
$s = $a->getArr(); 
echo $s[0];

Does PHP copy the array and the contents of the array when returning it?

From the point of view of the programmer, it works as if returning would copy the value, except when returning by reference. In terms of implementation, there are optimizations that avoid this happens, as long as it has no impact in the behavior of the script.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜