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 に答える