PHP 中的引用

发布于 2024-12-05 04:00:32 字数 425 浏览 0 评论 0原文

看看 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

街道布景 2024-12-12 04:00:32
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;
}

因此,您需要在函数声明中指定&,并按原样传递参数。

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.

べ映画 2024-12-12 04:00:32

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文