PHP 中的引用
看看 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;
}
我将在哪里放置“&”在此,如果我想在函数 test3 中设置私有变量 TestArray1 和 TestArray2 后对其进行编辑?
Looking at referencing in PHP is pretty much confusing me, can anyone explain to me how this would work:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因此,您需要在函数声明中指定
&
,并按原样传递参数。So you need to specify
&
in the function declaration, and pass parameter as-is.php 5.3 中的默认行为是通过引用传递对象。您可以使用 &符号来强制原始类型也通过引用传递,尽管您通常没有任何理由这样做。
您的示例可能会令人困惑,因为您似乎不在类内部,因此 private 修饰符没有意义。没有理由将成员变量传递到方法中,因为该方法本身可以直接访问它。
希望有帮助。
编辑:我还应该指出,显然数组不计为“默认按引用传递”的对象。即,&此处需要:codepad.viper-7.com/LBcr4m
The default behavior in php 5.3 is to pass objects by reference. 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