PHP通过引用传递:理解

时间:2015-11-19 04:09:44

标签: php reference

我正在学习php的基本概念。这是引用变量的代码。 有人可以帮我解释一下。

<?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$car = &$bar;

$bar = "My name is $bar";  // Alter $bar...

echo $bar ."\n\n";
echo $foo ."\n\n";                 // $foo, $car are altered too.
echo $car ."\n\n";                 // $foo, $car are altered too.
//My name is bob
//My name is bob
//My name is bob
?>

1 个答案:

答案 0 :(得分:0)

试试这个..

您可以通过引用函数传递变量,以便函数可以修改变量。语法如下:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
// $a is 6 here
?>

注意:函数调用上没有引用符号 - 仅限于函数定义。单独的函数定义足以通过引用正确传递参数。从PHP 5.3.0开始,当您使用&amp;时,您将收到一条警告,指出“call-time pass-by-reference”已被弃用。在foo(&amp; $ a);.从PHP 5.4.0开始,删除了调用时传递引用,因此使用它会引发致命错误。

通过参考

引用允许两个变量引用相同的内容。换句话说,变量指向其内容(而不是成为该内容)。通过引用传递允许两个变量指向不同名称下的相同内容。 &符号(&amp;)放在要引用的变量之前。

$a = 1;
$b = &$a; // $b references the same value as $a, currently 1
$b = $b + 1; // 1 is added to $b, which effects $a the same way
echo "b is equal to $b, and a is equal to $a";

<强>输出:

b is equal to 2, and a is equal to 2

当您希望简单地更改原始变量并将其再次返回到指定了新值的相同变量名称时,将其用于函数。

function add(&$var){ // The &amp; is before the argument $var
$var++;
}
$a = 1;
$b = 10;
add($a);
echo "a is $a,";
add($b);
echo " a is $a, and b is $b"; //

<强>输出:

a is 2, a is 2, and b is 11

您也可以使用foreach来改变数组:

$array = array(1,2,3,4);
foreach ($array as &$value){
$value = $value + 10;
}
unset ($value); // Must be included, $value remains after foreach loop
print_r($array);

**Output:**

Array ( [0] => 11 [1] => 12 [2] => 13 [3] => 14 )

价:http://php.net/manual/en/language.references.pass.php

http://www.phpreferencebook.com/samples/php-pass-by-reference/