在 PHP 5 中如何通过引用传递对象? [英] How do you pass objects by reference in PHP 5?
问题描述
在 PHP 5 中,您是否需要使用 &
修饰符来通过引用传递?例如,
In PHP 5, are you required to use the &
modifier to pass by reference? For example,
class People() { }
$p = new People();
function one($a) { $a = null; }
function two(&$a) { $a = null; )
在 PHP4 中,您需要 &
修饰符在更改后保持引用,但我对我读过的有关 PHP5 自动使用传递引用的主题感到困惑,除非明确克隆对象.
In PHP4 you needed the &
modifier to maintain reference after a change had been made, but I'm confused on the topics I have read regarding PHP5's automatic use of pass-by-reference, except when explicity cloning the object.
在 PHP5 中, &
修饰符是否需要为所有类型的对象(变量、类、数组等)通过引用传递?
推荐答案
您是否需要使用 &传递引用的修饰符?
are you required to use the & modifier to pass-by-reference?
从技术/语义上来说,答案是是,即使是对象也是如此.这是因为有两种方法可以传递/分配对象:通过引用或通过标识符.当函数声明包含 &
时,如:
Technically/semantically, the answer is yes, even with objects. This is because there are two ways to pass/assign an object: by reference or by identifier. When a function declaration contains an &
, as in:
function func(&$obj) {}
无论如何,参数将通过引用传递.如果你声明没有 &
The argument will be passed by reference, no matter what. If you declare without the &
function func($obj) {}
所有东西都将通过值传递,对象和资源除外,它们将通过标识符传递.什么是标识符?好吧,您可以将其视为对引用的引用.举个例子:
Everything will be passed by value, with the exception of objects and resources, which will then be passed via identifier. What's an identifier? Well, you can think of it as a reference to a reference. Take the following example:
class A
{
public $v = 1;
}
function change($obj)
{
$obj->v = 2;
}
function makezero($obj)
{
$obj = 0;
}
$a = new A();
change($a);
var_dump($a);
/*
output:
object(A)#1 (1) {
["v"]=>
int(2)
}
*/
makezero($a);
var_dump($a);
/*
output (same as before):
object(A)#1 (1) {
["v"]=>
int(2)
}
*/
那么为什么$a
传递给makezero
后不会突然变成整数呢?这是因为我们只覆盖了标识符.如果我们通过引用传递:
So why doesn't $a
suddenly become an integer after passing it to makezero
? It's because we only overwrote the identifier. If we had passed by reference:
function makezero(&$obj)
{
$obj = 0;
}
makezero($a);
var_dump($a);
/*
output:
int(0)
*/
现在 $a
是一个整数.因此,通过 identifier 传递和通过 reference 传递是有区别的.
Now $a
is an integer. So, there is a difference between passing via identifier and passing via reference.
这篇关于在 PHP 5 中如何通过引用传递对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!