如何在PHP 5中通过引用传递对象? [英] How do you pass objects by reference in PHP 5?

查看:63
本文介绍了如何在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?

从技术上/意义上讲,即使是对象,答案也是.这是因为有两种传递/分配对象的方法:通过引用或通过 identifier .当函数声明包含&时,例如:

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) {}

除对象和资源外,所有内容均按值传递,然后通过 identifier 传递.什么是标识符?好吧,您可以将其视为对参考的参考.请看以下示例:

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后为什么不突然变成整数?这是因为我们只改写了 identifier .如果我们通过了 reference :

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆