Are PHP5 objects passed by reference?

后端 未结 8 737
抹茶落季
抹茶落季 2020-11-27 03:45

I can\'t seem to get any consistent info on this. Different sources appear to say different things and the venerable php.net itself (appears) not to explicitly stat

相关标签:
8条回答
  • 2020-11-27 04:49

    Objects are passed (and assigned) by reference. No need to use address of operator.

    Granted what I typed is an oversimplification but will suit your purposes. The documentation states:

    One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.

    A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

    For a more detailed explanation (explains the oversimplification as well as identifiers) check out this answer.

    0 讨论(0)
  • 2020-11-27 04:51

    It seems to be a little more precise, the value of an object is passed by value, but the value of an object itself is a pointer. This is different from just passing a reference.

    On http://www.php.net/manual/en/language.oop5.references.php the example listed is nice. In the first set, $a = NULL; doesn't affect $b since $a was just a pointer. In the second set, $c = NULL; causes $d to be NULL as well since $d is a reference to $c.

    <?php
    class A {
        public $foo = 1;
    }  
    
    $a = new A;
    $b = $a;
    $a->foo = 2;
    $a = NULL;
    echo $b->foo."\n"; // 2
    
    $c = new A;
    $d = &$c;
    $c->foo = 2;
    $c = NULL;
    echo $d->foo."\n"; // Notice:  Trying to get property of non-object...
    ?> 
    
    0 讨论(0)
提交回复
热议问题