1

我正在阅读在深渊中求生。在那里我阅读了以下部分:

    $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);)

4

2 回答 2

3

对象总是通过引用传递。

于 2012-09-14T08:39:19.520 回答
1

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

# 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
于 2012-09-14T08:38:51.470 回答