Php 什么是&;在函数名表示之前?

Php 什么是&;在函数名表示之前?,php,function,Php,Function,函数名前的&表示什么 这是否意味着$result是通过引用而不是通过值返回的? 如果是,那么它是否正确?我记得你不能返回对局部变量的引用,因为一旦函数退出它就会消失 function &query($sql) { // ... $result = mysql_query($sql); return $result; } 在实践中,这种语法在哪里使用 这是否意味着$result是通过引用而不是通过值返回的 对 在实践中,这种语法在哪里使用 这在PHP4脚本中更为普遍,默认情况下,对

函数名前的
&
表示什么

这是否意味着
$result
是通过引用而不是通过值返回的? 如果是,那么它是否正确?我记得你不能返回对局部变量的引用,因为一旦函数退出它就会消失

function &query($sql) {
 // ...
 $result = mysql_query($sql);
 return $result;
}
实践中,这种语法在哪里使用

这是否意味着
$result
是通过引用而不是通过值返回的

实践中,这种语法在哪里使用


这在PHP4脚本中更为普遍,默认情况下,对象是通过值传递的。

为了回答问题的第二部分,我不得不在这里使用它:Magic getters

class FooBar {
    private $properties = array();

    public function &__get($name) {
        return $this->properties[$name];
    }

     public function __set($name, $value) {
        $this->properties[$name] = $value;
    }
}
如果我没有在那里使用
&
,这是不可能的:

$foobar = new FooBar;
$foobar->subArray = array();
$foobar->subArray['FooBar'] = 'Hallo World!';
相反,PHP会抛出一个类似“无法间接修改重载属性”的错误

好的,这可能只是一个绕过PHP中一些错误设计的方法,但它仍然很有用

但老实说,我现在想不出另一个例子。但我敢打赌有一些罕见的用例

这是否意味着
$result
是通过引用而不是通过值返回的

否。区别在于它可以通过引用返回。例如:

<?php
function &a(&$c) {
    return $c;
}
$c = 1;
$d = a($c);
$d++;
echo $c; //echoes 1, not 2!

-1用于声明$result的值只存在于函数中,因此是无用的。@nikic:你对php5中的对象是按值传递的说法有任何支持吗?@nikic:我认为这不能证明对象是按值传递的。如果将局部变量设置为新值,则它不是同一对象。您必须编写一个函数来修改某个可变类型的对象,并显示传入的值没有在外部更改,以证明参数是通过值传递的(复制的)。@nikic:您的示例有点复杂,因为您混合了对象和字符串数据类型。一个正确的例子是:
$a=newstdclass$a->prop='foo';函数测试($b){$b->prop='bar';}测试($a);回声$a->prop如您所见,对象通过ref传递:)除非另有说明,否则PHP调用的“对象”总是通过值传递。PHP4和PHP5之间的区别在于,在PHP5中,您传递对对象的引用。如果函数名称前没有使用a&定义函数,您是否仍然可以返回带有引用而不是值的变量?
<?php
function &a(&$c) {
    return $c;
}
$c = 1;
$d = &a($c);
$d++;
echo $c; //echoes 2
  <?php
    // You may have wondered how a PHP function defined as below behaves:
    function &config_byref()
    {
        static $var = "hello";
        return $var;
    }
    // the value we get is "hello"
    $byref_initial = config_byref();
    // let's change the value
    $byref_initial = "world";
    // Let's get the value again and see
    echo "Byref, new value: " . config_byref() . "\n"; // We still get "hello"
    // However, let’s make a small change:
    // We’ve added an ampersand to the function call as well. In this case, the function returns "world", which is the new value.
    // the value we get is "hello"
    $byref_initial = &config_byref();
    // let's change the value
    $byref_initial = "world";
    // Let's get the value again and see
    echo "Byref, new value: " . config_byref() . "\n"; // We now get "world"
    // If you define the function without the ampersand, like follows:
    // function config_byref()
    // {
    //     static $var = "hello";
    //     return $var;
    // }
    // Then both the test cases that we had previously would return "hello", regardless of whether you put ampersand in the function call or not.