将参数变量值传递给函数后如何更改?

时间:2012-09-14 08:36:07

标签: php

我正在阅读Survive the deep end。在那里,我阅读了以下部分:

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

mapper :: save的代码如下:

    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

正如您所看到的那样,变量未通过引用传递,那么在调用函数的$ entry中如何更改该值? (即; $ this-> _mapper-> save($ entry); $ this-> assertEquals(123,$ entry-> id);)

2 个答案:

答案 0 :(得分:3)

对象总是通过引用传递。

答案 1 :(得分:1)

对象通过引用自动传递。要传递副本,clone您的对象。

# 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