2010-10-18 40 views
1

這涉及到一個問題:How does the "&" operator work in a PHP function?是否有簡單的PHP代碼來區分「傳遞對象作爲參考」與「傳遞對象引用作爲值」?

有沒有簡單的代碼來顯示傳遞對象作爲參考

的區別

VS

傳遞對象的引用作爲價值?

+0

一直沒有康拉德魯道夫已經提供[示例](http://pastie.org/1229473)? – BoltClock 2010-10-18 09:26:19

+0

有趣......我認爲在C社區中,通過引用傳遞對象與傳遞其引用的值相同...我在上面的代碼示例中看到的內容將被稱爲「通過其引用作爲參考」 – 2010-10-18 09:30:01

+0

您可以看到這個鏈接例如:http://stackoverflow.com/questions/879/are-php-variables-passed-by-value-or-by-reference – Mahsin 2016-07-25 12:34:52

回答

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 
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'; 
2

您可以參考變量傳遞給函數。該功能將能夠修改原始變量。

可以通過在函數定義參考限定所述通道:

<?php 
function changeValue(&$var) 
{ 
    $var++; 
} 

$result=5; 
changeValue($result); 

echo $result; // $result is 6 here 
?> 
相關問題