1

これは次の質問に関連しています: PHP 関数で「&」演算子はどのように機能しますか?

違いを示す簡単なコードはありますか

オブジェクトを参照として渡す

オブジェクトの参照を値として渡しますか?

4

3 に答える 3

0
<?php
class X {
    var $abc = 10; 
}
class Y {
    var $abc = 20; 
    function changeValue(&$obj){//1>here the object,$x is a reference to the object,$obj.hence it is "passing the object's reference as value"
        echo 'inside function :'.$obj->abc.'<br />';//2>it prints 10,bcz it accesses the $abc property of class X, since $x is a reference to $obj.
        $obj = new Y();//but here a new instance of class Y is created.hence $obj became the object of class Y.
        echo 'inside function :'.$obj->abc.'<br />';//3>hence here it accesses the $abc property of class Y.
    }
}
$x = new X();
$y = new Y();

$y->changeValue($x);//here the object,$x is passed as value.hence it is "passing the object as value"
echo $x->abc; //4>As the value has been changed through it's reference ,hence it calls $abc property of class Y not class X.though $x is the object of class X
?>

o/p :

inside function :10
inside function :20
20
于 2013-07-02T10:22:30.457 に答える
0

これはどう:

<?php
class MyClass {
    public $value = 'original object and value';
}

function changeByValue($originalObject) {
    $newObject = new MyClass();
    $newObject->value = 'new object';

    $originalObject->value = 'changed value';

    // This line has no affect outside the function, and is
    // therefore redundant here (and so are the 2 lines at the
    // the top of this function), because the object
    // "reference" was passed "by value".
    $originalObject = $newObject;
}

function changeByReference(&$originalObject) {
    $newObject = new MyClass();
    $newObject->value = 'new object';

    $originalObject->value = 'changed value';

    // This line changes the object "reference" that was passed
    // in, because the "reference" was passed "by reference".
    // The passed in object is replaced by a new one, making the
    // previous line redundant here.
    $originalObject = $newObject;
}

$object = new MyClass();
echo $object->value;  // 'original object and value';

changeByValue($object)
echo $object->value;  // 'changed value';

$object = new MyClass();
echo $object->value;  // 'original object and value';

changeByReference($object)
echo $object->value;  // 'new object';
于 2014-02-23T17:58:39.500 に答える