gpt4 book ai didi

PHP 引用 : An understanding

转载 作者:可可西里 更新时间:2023-11-01 13:24:36 28 4
gpt4 key购买 nike

在我创建和构建我的一些 php 应用程序的过程中,我看到了变量、= 和类名前面的 & 符号。

我知道这些是 PHP 引用资料,但我看过和看过的文档似乎只是没有以我理解或混淆的方式解释它。你如何解释我看到的以下示例,使它们更容易理解。

  public static function &function_name(){...}

$varname =& functioncall();

function ($var, &$var2, $var3){...}

非常感谢

最佳答案

假设你有两个函数

$a = 5;
function withReference(&$a) {
$a++;
}
function withoutReference($a) {
$a++;
}

withoutReference($a);
// $a is still 5, since your function had a local copy of $a
var_dump($a);
withReference($a);
// $a is now 6, you changed $a outside of function scope
var_dump($a);

因此,通过引用传递参数允许函数在函数范围之外修改它。

现在是第二个例子。

你有一个返回引用的函数

class References {
public $a = 5;
public function &getA() {
return $this->a;
}
}

$references = new References;
// let's do regular assignment
$a = $references->getA();
$a++;
// you get 5, $a++ had no effect on $a from the class
var_dump($references->getA());

// now let's do reference assignment
$a = &$references->getA();
$a++;
// $a is the same as $reference->a, so now you will get 6
var_dump($references->getA());

// a little bit different
$references->a++;
// since $a is the same as $reference->a, you will get 7
var_dump($a);

关于PHP 引用 : An understanding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15118863/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com