10

考虑:

public function & get($name, $default = null)

为什么&

4

3 回答 3

12

In PHP's syntax, this means that the function returns a reference instead of a value. For example:

<?php
    $foo = 'foo';

    function & get_foo_ref ()
    {
        global $foo;
        return $foo;
    }

    // Get the reference to variable $foo stored into $bar
    $bar = & get_foo_ref();
    $bar = 'bar';

    echo $foo; // Outputs 'bar', since $bar references to $foo.
?>

In the above example, removing the & from the function declaration would make the $foo variable still contain 'foo', since only the value, not the reference was returned from the function.

This was used more often in PHP4, because it did not pass objects by their reference and cloned them instead. Because of this, object variables had to be passed by reference to avoid unwanted cloning. This is no longer the case in PHP5 and references should not be used for this purpose.

However, functions that return references are not completely useless either (or bad practice, when not used for replacing object references).

For example, personally I've used them when creating a script that passes a "path" to an function, which returns reference to variable in that path allowing me to set value to it and read the value. Due to the recursive nature of the function, returning the reference was needed.

By rithiur

于 2010-03-19T14:54:16.263 回答
11

这意味着它返回对结果的引用,而不是它的副本。

在 PHP 中返回引用

于 2010-03-19T14:50:22.973 回答
0

PHP 的引用传递元字符。请参阅通过引用传递

于 2010-03-19T14:51:26.593 回答