PHP 5 passing class Object as parameter, is it always a pointer or a copy or a clone?

php, scope

Solution

In PHP When you pass object as parameter, it is copy of the reference. So:

$ob = new StdClass;
$ob->var = "Lorem";

function aa($o) {
    $o->var="Ipsum";
}
aa($ob);
echo $ob->var;

this will output `Ipsum`, but if you assign other object to that $o reference:

function aa($o) {
    $o = new StdClass;
    $o->var="Ipsum";
}

It will output `Lorem` - because $ob still points to previously created object.

By the way: If you change function definition to `function aa(&$o)`. Now it will output `Ipsum` again, because $o is reference to $ob reference :)

To sum up: In PHP by default parameters are passed by value - also if they are objects! But! In code `$ob = new StdClass;`, `$ob` is reference to the object. So by default we will pass copy of the reference. They will point to the same objects. But if you change passed variable (`$o = new StdClass;`), `$ob` still points to the same object. That's why after that modification given example will output `Lorem`.

You can pass parameters by reference using ampersand (&), but in case of objects it is usually useless.

Problem

I have a question about passing object as parameter. When we pass a variable, it creates a copy, but looks like object is always a reference pointer, is this correct? I have tested with the following example code: ``` class Base { private $var; function set ($var) { $this->var = $var; } function show () { echo $this->var, '<br>'; } } class Car { private $obj; function __construct($obj) { $this->obj = $obj; } function set ($var) { $this->obj->set($var); } function show() { $this->obj->show(); } } class Bus { private $obj; function __construct($obj) { $this->obj = $obj; } function set ($var) { $this->obj->set($var); } function show() { $this->obj->show(); } } ``` And by running ``` $base = new Base(); $base->set('one'); $base->show(); // one $bus = new Bus($base); $bus->show(); // one $car = new Car($base); $car->set('two'); $car->show(); // two $base->show(); // two $bus->show(); // two ``` The display result is: ``` one one two two two ``` So changing the Base class's variable anywhere even it was passed as parameter into a function or another class will affect all of them, so does this mean it's always pointing to a same object as a pointer? Thank you.

Original source