代码之家  ›  专栏  ›  技术社区  ›  Zacky112

函数名前的&表示什么?

  •  22
  • Zacky112  · 技术社区  · 15 年前

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

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

    function &query($sql) {
     // ...
     $result = mysql_query($sql);
     return $result;
    }
    

    这种语法在哪里使用 实践 ?

    4 回复  |  直到 11 年前
        1
  •  8
  •   BoltClock    15 年前

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

    对。

    这种语法在哪里使用 实践 ?

    这在PHP 4脚本中更为普遍,默认情况下,对象是按值传递的。

        2
  •  7
  •   NikiC    15 年前

    为了回答你的问题的第二部分,这里有一个地方我不得不用它:魔法消息灵通!

    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中一些错误设计的技巧,但它仍然很有用。

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

        3
  •  5
  •   Artefacto    15 年前

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

    不,不同的是 可以 通过引用返回。例如:

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

    要通过引用返回,您必须执行以下操作:

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

    这种语法在哪里使用 实践 ?

    实际上,只要希望函数的调用者操纵被调用者拥有的数据而不告诉他,就可以使用它。这很少使用,因为这违反了封装,您可以将返回的引用设置为所需的任何值;被调用方将无法验证它。

    尼基克举了一个很好的例子来说明这一点。

        4
  •  0
  •   sunny kashyap    6 年前
      <?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.
    
    推荐文章