kaushik
kaushik

Reputation: 2492

How the argument variables value changed after passing it to a function?

I am reading Survive the deep end. There I read the following section:

    $this->_mapper->save($entry);
    $this->assertEquals(123, $entry->id);

Code for mapper::save is as follows:

    public function save(ZFExt_Model_Entry $entry) {
    if(!$entry->id) {
        $data = array(
            'title' => $entry->title,
            'content' => $entry->content,
            'published_date' => $entry->published_date,
            'author_id' => $entry->author->id
        );
        $entry->id = $this->_getGateway()->insert($data);
                    ....contd

As you can see the variable is not passed by reference, then how the value will get changed in $entry in the calling function ? (i.e; $this->_mapper->save($entry); $this->assertEquals(123, $entry->id);)

Upvotes: 1

Views: 71

Answers (2)

Bugs
Bugs

Reputation: 1452

Objects are passed by reference automatically. To pass a copy, clone your object.

# Primitives are not passed by reference by default
$a = 12;

function setValue($var, $value)
{
    $var = $value;
}
setValue($a, 0);
echo $a; # 12

function setValueByRef(&$var, $value)
{
    $var = $value;
}
setValueByRef($a, 0);
echo $a; # 0

# Objects are always passed by reference
$obj = new stdClass();
$obj->p = 8;

function setAttribute($object, $attribute, $value)
{
    $object->$attribute = $value;
}
setAttribute($obj, 'p', 5);
echo $obj->p; # 5

# and this case, & does not change the behaviour
function setAttributeByRef(&$object, $attribute, $value)
{
    $object->$attribute = $value;
}
setAttributeByRef($obj, 'p', 7);
echo $obj->p; # 7

# You can clone your object not to affect it
$clonedObj = clone $obj;
setAttribute($clonedObj, 'p', 1);
echo $obj->p; # still 7
echo $clonedObj->p; # 1

# Moreover, object properties are treated like other variables
setValue($obj->p, 0);
echo $obj->p; # still 7

setValueByRef($obj->p, 0);
echo $obj->p; # 0

Upvotes: 1

Madara's Ghost
Madara's Ghost

Reputation: 174957

Objects are always passed by reference.

Upvotes: 3

Related Questions