首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Passing by Reference

You can pass a variable by reference to a function so the function can modify the variable. The syntax is as follows:

代码语言:javascript
复制
<?php
function foo(&$var)
{
    $var++;
}

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

Note: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

The following things can be passed by reference:

  • Variables, i.e. foo($a)
  • New statements, i.e. foo(new foobar())
  • References returned from functions, i.e.:

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

See more about returning by reference.

No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:

代码语言:javascript
复制
<?php
function foo(&$var)
{
    $var++;
}
function bar() // Note the missing &
{
    $a = 5;
    return $a;
}
foo(bar()); // Produces fatal error as of PHP 5.0.5, strict standards notice
            // as of PHP 5.1.1, and notice as of PHP 7.0.0

foo($a = 5); // Expression, not variable
foo(5); // Produces fatal error
?>

← What References Are Not

Returning References →

代码语言:txt
复制
 © 1997–2017 The PHP Documentation Group

Licensed under the Creative Commons Attribution License v3.0 or later.

扫码关注腾讯云开发者

领取腾讯云代金券