开发者

Are objects in array passed by reference?

in a situation like that below,

class my_class {

    public __construct($params = array()){

        **** do something
    } 

 }

 $other_object = new some_class();

 $object = new my_class(array(
                         'var1' => 'test' 
                         'object' => $other_object开发者_运维百科));

$other_object will be passed by reference or by value?


Objects are always references, except you clone it explicitly.

You can use spl_object_hash() to retrieve the "object id" and then compare them against each other. Remember, that once an object is removed from the memory by the garbage collector, the ID may get reused.


Here is one example that shows referenced object every where... http://codepad.org/HK6Oo4xL


Objects in php are passed by value. See this answer for details.


Objects in PHP 5 are always passed by reference. With the help of debug_zval_dump() you can check refcount for variable to calculate number of references to the object instance. Pay attention to the note in documentation, you will found many interesting things about passing a variable to a function.


as of PHP 5 PHP object variable contain the reference or identifier to the actual variable. here is an example to demonstrate this.

class test{
public $test = 1;
}

$obj1 = new test;
$orginal = [$obj1,array(2),3];
$copy = $orginal;
echo 'orginal array';
var_dump($orginal);
echo 'copy of orginal';
var_dump($copy);

//after changing
$copy[0]->test = 'changed';
$copy[1][0] = 'changed';
$copy[3] = 'changed';
echo 'orginal array after changing its copy';
var_dump($original);
echo 'copy of orginal after changing';
var_dump($copy);

the output for this is

original array
array (size=3)
  0 => 
    object(test)[38]
      public 'test' => int 1
  1 => 
    array (size=1)
      0 => int 2
  2 => int 3

copy of original
array (size=3)
  0 => 
    object(test)[38]
      public 'test' => int 1
  1 => 
    array (size=1)
      0 => int 2
  2 => int 3

original array after changing its copy
array (size=3)
  0 => 
    object(test)[38]
      public 'test' => string 'changed' (length=7)
  1 => 
    array (size=1)
      0 => int 2
  2 => int 3

copy of original after changing
array (size=3)
  0 => 
    object(test)[38]
      public 'test' => string 'changed' (length=7)
  1 => 
    array (size=1)
      0 => string 'changed' (length=7)
  2 => string 'changed' (length=7)

when the object in the copy is changed then the original object is also changed but the array and variable remain unchanged since they are passed as value.

more info about object reference refer : Objects and reference

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜