duanji1043 2010-10-18 09:16
浏览 45

是否有简单的PHP代码来区分“将对象作为引用传递”与“将对象引用作为值传递”?

This is related to question: How does the "&" operator work in a PHP function?

Is there simple code to show the difference between

passing the object as reference

vs

passing the object's reference as value?

  • 写回答

3条回答 默认 最新

  • doushou8730 2013-07-02 10:22
    关注
    <?php
    class X {
        var $abc = 10; 
    }
    class Y {
        var $abc = 20; 
        function changeValue(&$obj){//1>here the object,$x is a reference to the object,$obj.hence it is "passing the object's reference as value"
            echo 'inside function :'.$obj->abc.'<br />';//2>it prints 10,bcz it accesses the $abc property of class X, since $x is a reference to $obj.
            $obj = new Y();//but here a new instance of class Y is created.hence $obj became the object of class Y.
            echo 'inside function :'.$obj->abc.'<br />';//3>hence here it accesses the $abc property of class Y.
        }
    }
    $x = new X();
    $y = new Y();
    
    $y->changeValue($x);//here the object,$x is passed as value.hence it is "passing the object as value"
    echo $x->abc; //4>As the value has been changed through it's reference ,hence it calls $abc property of class Y not class X.though $x is the object of class X
    ?>
    

    o/p :

    inside function :10
    inside function :20
    20
    
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致