Are objects in PHP passed by value or reference?

Why not run the function and find out?

$b = new Bar;
echo $b->getFoo(5)->value;
$b->test();
echo $b->getFoo(5)->value;

For me the above code (along with your code) produced this output:

Foo #5
My value has now changed

This isn't due to "passing by reference", however, it is due to "assignment by reference". In PHP 5 assignment by reference is the default behaviour with objects. If you want to assign by value instead, use the clone keyword.


You can refer to http://ca2.php.net/manual/en/language.oop5.references.php for the actual answer to your question.

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.

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.


They are passed by value in PHP 4 and by reference in PHP 5. In order to pass objects by reference in PHP 4 you have to explicitly mark them as such:

$obj = &new MyObj;

Tags:

Php

Oop