超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<引用不是什么引用返回>
Last updated: Fri, 22 Jun 2007

引用传递

你可以将一个变量通过引用传递给函数,这样该函数就可以修改其参数的值。语法如下:

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

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

注意在函数调用时没有引用符号 - 只有函数定义中有。光是函数定义就足够使参数通过引用来正确传递了。

以下内容可以通过引用传递:

  • 变量,例如 foo($a)

  • New 语句,例如 foo(new foobar())

  • 从函数中返回的引用,例如:

    <?php
    function &bar()
    {
      
    $a = 5;
       return
    $a;
    }
    foo(bar());
    ?>

    详细解释见引用返回

任何其它表达式都不能通过引用传递,结果未定义。例如下面引用传递的例子是无效的:

<?php
function bar() // Note the missing &
{
  
$a = 5;
   return
$a;
}
foo(bar());

foo($a = 5) // 表达式,不是变量
foo(5) // 常量,不是变量
?>

这些条件是 PHP 4.0.4 以及以后版本有的。




add a note add a note User Contributed Notes
引用传递
blistwon-php at designfridge dot com
18-Jan-2004 10:33
One thing to note about passing by reference. If you plan on assigning the reference to a new variable in your function, you must use the reference operator in the function declaration as well as in the assignment. (The same holds true for classes.)

-------------------------------------------------------
CODE
-------------------------------------------------------
function f1(&$num) {
$num++;
}
function f2(&$num) {
$num1 = $num;
$num1++;
}
function f3(&$num) {
$num1 = &$num;
$num1++;
}

$myNum = 0;
print("Declare myNum: " . $myNum . "<br />\n");
f1($myNum);
print("Pass myNum as ref 1: " . $myNum . "<br />\n");
f2($myNum);
print("Pass myNum as ref 2: " . $myNum . "<br />\n");
f3($myNum);
print("Pass myNum as ref 3: " . $myNum . "<br />\n");
-------------------------------------------------------

-------------------------------------------------------
OUTPUT
-------------------------------------------------------
Declare myNum: 0
Pass myNum as ref 1: 1
Pass myNum as ref 2: 1
Pass myNum as ref 3: 2
-------------------------------------------------------

Hope this helps people trying to detangle any problems with pass-by-ref.

<引用不是什么引用返回>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22