是否有简单的 PHP 代码来区分“将对象作为引用传递”与“将对象引用作为值传递”?
Posted
技术标签:
【中文标题】是否有简单的 PHP 代码来区分“将对象作为引用传递”与“将对象引用作为值传递”?【英文标题】:Is there simple PHP code to distinguish "Passing the object as reference" vs "Passing the object reference as value"? 【发布时间】:2011-04-26 20:19:53 【问题描述】:这与问题有关:How does the "&" operator work in a php function?
有没有简单的代码来显示两者的区别
将对象作为引用传递
对比
将对象的引用作为值传递?
【问题讨论】:
康拉德鲁道夫不是已经提供了an example吗? 很有趣...我认为在C社区中,通过引用传递对象与将其引用作为值传递相同...我在上面的代码示例中看到的将称为“传递它的参考作为参考” 你可以看到这个链接例如:***.com/questions/879/… 【参考方案1】:您可以通过引用将变量传递给函数。该函数将能够修改原始变量。
可以在函数定义中通过引用来定义段落:
<?php
function changeValue(&$var)
$var++;
$result=5;
changeValue($result);
echo $result; // $result is 6 here
?>
【讨论】:
【参考方案2】:<?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
【讨论】:
【参考方案3】:这个怎么样:
<?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';
【讨论】:
以上是关于是否有简单的 PHP 代码来区分“将对象作为引用传递”与“将对象引用作为值传递”?的主要内容,如果未能解决你的问题,请参考以下文章