doutao1282 2017-02-02 20:30
浏览 35
已采纳

当你通过引用传递一个对象时,会发生什么?

a question for anyone who knows. The PHP documentation (for php5) clearly states that you don't pass objects by references in php, because for a method that accepts an object, the value actually being passed is an "object identifier which allows object accessors to find the actual object". The question is, what is happening when you actually do do this?

Consider the following code:

<?php
function foo(&$arg){
    if(is_array($arg)){
         print $arg['foo'];
    }
    if(is_object($arg)){
        print $arg->{'foo'};
    }
}
$o1 = new \stdClass;
$o1->foo = 'bar';
$a1 = ['foo'=>'bar'];
print sprintf("O1 foo: %s", foo($o1));
print sprintf("a1 foo: %s", foo($a1));

This correctly outputs:

o1 foo: bar
a1 foo: bar

The question is why? Can anyone describe what's happening with this object identifier reference that still allows accessing the actual object?

  • 写回答

1条回答 默认 最新

  • douluoqiu4538 2017-02-02 20:38
    关注

    Any variable that holds an object is not holding the object directly. It holds an identifier of the object. Imagine it as the object living somewhere in an object pool having a number attached to it, e.g. #5. All the variable contains is "object #5". PHP knows that the variable refers to an object and that it's supposed to be object #5.

    Whenever you work with such a variable holding an object reference, PHP looks up the referenced object from the object pool.

    When you pass such a variable into a function, PHP makes a copy of that reference. There are then two variables holding the content "object #5". Not the object itself has been copied, just this tiny note which says "object #5".

    When you pass such a variable into a function by reference, well, you're passing that note "object #5" by reference. PHP won't make a copy of it. But it's still just a variable saying "object #5", so when you're trying to work with it, PHP will look up the object from the pool.

    This object reference mechanism is not the same as the & pass-by-reference mechanism. The object reference mechanism works exactly the same as all other pass-by-value operations; it's just that a value which represents a reference to an object is always being treated in a specific way (PHP has to look up the actual object elsewhere).

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

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退