我已经在我的旅程中看到了creaitng和构建我的一些php应用程序,vars,=和类名前面的&符号.
我知道这些是PHP参考资料,但我看过和看过的文档似乎并没有以我理解或混淆的方式解释它.你如何解释我见过的以下例子,使它们更容易理解.
public static function &function_name(){...}
$varname =& functioncall();
function ($var, &$var2, $var3){...}
Run Code Online (Sandbox Code Playgroud)
非常感激
假设你有两个函数
$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);
Run Code Online (Sandbox Code Playgroud)
因此,通过引用传递参数允许函数在函数作用域之外修改它。
现在是第二个例子。
你有一个返回引用的函数
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |