tags:

views:

406

answers:

3

In this code:

<?php
class Foo
{
    var $value;

    function foo($value)
    {
        $this->setValue($value);
    }

    function setValue($value)
    {
        $this->value=$value;
    }
}

class Bar
{
    var $foos=array();

    function Bar()
    {
        for ($x=1; $x<=10; $x++)
        {
            $this->foos[$x]=new Foo("Foo # $x");
        }
    }

    function getFoo($index)
    {
        return $this->foos[$index];
    }

    function test()
    {
        $testFoo=$this->getFoo(5);
        $testFoo->setValue("My value has now changed");
    }
}
?>

When the method Bar::test() is run and it changes the value of foo # 5 in the array of foo objects, will the actual foo # 5 in the array be affected, or will the $testFoo variable be only a local variable which would cease to exist at the end of the function?

+2  A: 

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;
Emil H
+1  A: 

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.

tomzx
+3  A: 

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.

yjerem
what happens with this on php 4?
Click Upvote
PHP4 will behave as 'clone'
Evert
Can php 4 be configured to do assignment by reference in the same manner as php 5?
Click Upvote
yjerem