简体   繁体   English

在PHP中引用

[英]Referencing in PHP

Looking at referencing in PHP is pretty much confusing me, can anyone explain to me how this would work: 看看PHP中的引用让我感到困惑,任何人都可以向我解释这是如何工作的:

private $TestArray1 = Array()
private $TestArray2 = Array()

private function test1(){
$this->test2($this->TestArray1);
$this->test2($this->TestArray2);
}

private function test2($Array){
$this->test3($Array);
}

private function test3($Array){
$Array[0] = 1;
}

Where would I be putting the "&" in this, if I wanted to have the private variables TestArray1 and TestArray2 be edited, after it is set in function test3? 如果我想在函数test3中设置私有变量TestArray1和TestArray2,我将把“&”放在哪里?

private $TestArray1 = Array()
private $TestArray2 = Array()

private function test1(){
$this->test2($this->TestArray1);
$this->test2($this->TestArray2);
}

private function test2(&$Array){
$this->test3($Array);
}

private function test3(&$Array){
$Array[0] = 1;
}

So you need to specify & in the function declaration, and pass parameter as-is. 因此,您需要在函数声明中指定& ,并按原样传递参数。

The default behavior in php 5.3 is to pass objects by reference. php 5.3中的默认行为是通过引用传递对象。 You can use the & symbol to force primitive types to be passed by reference too, though you normally won't have any reason to do this. 您也可以使用&符号强制原始类型通过引用传递,尽管您通常没有任何理由这样做。

Your example is potentially confusing, as you don't seem to be inside of a class, so the private modifiers don't make sense. 你的例子可能令人困惑,因为你似乎不在一个类中,所以私有修饰符没有意义。 No reason to pass a member variable into a method, as the method could access it directly itself. 没有理由将成员变量传递给方法,因为该方法可以直接访问它自己。

Hope that helps. 希望有所帮助。

EDIT: And I also should point out that apparently arrays don't count as object for the "default pass by reference." 编辑:我还应该指出,显然数组不算作“默认通过引用传递”的对象。 That is, the & is required here: codepad.viper-7.com/LBcr4m 也就是说,这里需要&:codepad.viper-7.com/LBcr4m

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM