我在创建和构建我的一些 php 应用程序的过程中看到了 var 前面的 & 符号、= 和类名。
我知道这些是 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);
参考函数
$name = 'alfa';
$address = 'street';
//declaring the function with the $ tells PHP that the function will
//return the reference to the value, and not the value itself
function &function_name($what){
//we need to access some previous declared variables
GLOBAL $name,$address;//or at function declaration (use) keyword
if ($what == 'name')
return $name;
else
return $address;
}
//now we "link" the $search variable and the $name one with the same value
$search =& function_name('name');
//we can use the result as value, not as reference too
$other_search = function_name('name');
//any change on this reference will affect the "$name" too
$search = 'new_name';
var_dump($search,$name,$other_search);
//will output string 'new_name' (length=8)string 'new_name' (length=8)string 'alfa' (length=4)
通常,您将方法与实现相同接口的对象一起使用,并且您希望选择接下来要使用的对象。
通过引用传递:
function ($var, &$var2, $var3){...}
我相信您已经看到了这些示例,所以我将解释如何以及何时使用它。基本场景是您何时有一个大逻辑要应用于当前对象/数据,并且您不希望制作更多副本(在内存中)。希望这可以帮助。