douzhu3367 2016-11-08 22:25
浏览 70
已采纳

类成员引用PHP中的另一个对象

First code and then the question:

class MyArray
{
    private $arrayRef;

    function __construct(&$array){
        $this->arrayRef = $array;
    }

    function addElement($newElement){
        $this->arrayRef[] = $newElement;
    }

    function print(){
        print_r($this->arrayRef);
    }
}

$array = ['first', 'second'];
$arrayObject = new MyArray($array);
$arrayObject->addElement('third');

print_r($array); // prints array containing 2 elements
echo '<br/>';
$arrayObject->print(); // prints array containing 3 elements

Class member $arrayRef, in this example doesn't work as a reference to another array provided in constructor. Argument in constructor is passed by reference, but I guess that doesn't make member $arrayRef also a reference to that array as well.

Why doesn't it work like that and how to make it work?

If you still don't get what I mean: first print_r prints array containing 2 elements, even thought it may be expected to contain 3. When I pass third element to $arrayObject via addElement() I also want it to be added in the $array that I passed to constructor of class.

  • 写回答

1条回答 默认 最新

  • douwei1950 2016-11-08 22:37
    关注

    The answer is actually quite simple. Yes, you pass the array by reference via &$array but this reference gets lost when you assign/copy it to the member variable. To keep the reference, you can use the =& operator like so

    $this->arrayRef =& $array;
    

    See it work in this fiddle. You can read more about it in this question/answer (just look for reference).

    Beware not to use &= (which does a bitwise operation) instead of =& (which assigns by reference).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算