Are objects in PHP assigned 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.

Leave a Comment