【问题标题】:PHP: Assigning, Passing and Returning ReferencesPHP:分配、传递和返回引用
【发布时间】:2016-07-29 10:57:59
【问题描述】:

我已经阅读了这篇关于 PHP 引用的文章。

PHP References: How They Work, and When to Use Them

我知道它的语法,但对于何时在 PHP 中使用引用有点困惑。你能给我一个我可以应用参考的真实世界的例子吗?是否有必要使用引用或者我可以使用正常格式的函数?引用的真正目的是什么?

请你解释一下,我很容易理解。

【问题讨论】:

    标签: php reference


    【解决方案1】:

    使用引用的原因是为了修改传递给函数的值。

    这是一个例子

    $nameOfUser = "Mr. Jones";
    
    function changeName($name) { // Not passing the value by reference
        $name = "Foo";
    
        return $name;
    }
    
    changeName($nameOfUser);
    
    /**
     * The echo below will output "Mr. Jones" since the changeName() function
     * doesn't really change the value of the variable we pass in, since we aren't
     * passing in a variable by reference. We are only passing in the value of the
     * $nameOfUser variable, which in this case is "Mr. Jones".
     */
    echo $nameOfUser;
    
    $nameOfUser = changeName($nameOfUser);
    
    /**
     * This echo below will however output "Foo" since we assigned the returning
     * value of the changeName() function to the variable $nameOfUser
     */
    echo $nameOfUser;
    

    现在,如果我想在上面的第二个示例中获得与引用相同的结果,我会这样做:

    $nameOfUser = "Mr. Jones";
    
    function changeName(&$name) { // Passing the value by reference
        $name = "Foo";
    
        return $name;
    }
    
    changeName($nameOfUser);
    
    /**
     * The echo below will output "Foo" since the changeName() function
     * changed the value of the variable we passed in by reference
     */
    echo $nameOfUser;
    

    我希望我的示例是可以理解的,并且希望我能让您更好地了解引用的工作原理。

    我没有示例说明何时需要引用,因为我个人认为返回值并以这种方式设置会更好。修改传入函数的变量可能会使使用该函数的用户感到困惑。

    【讨论】:

    • -使用引用有什么好处吗?
    • 唯一的好处是 PHP 不需要创建另一个变量,因为它只使用指向第一个变量的指针。但我认为您不会注意到性能方​​面的任何差异。我认为如果你使用引用只会让代码更难理解。
    • 那为什么在 PHP 中包含引用会迷惑程序员呢?
    • 我认为这个答案很好地解释了它为什么存在:stackoverflow.com/a/5479167/5259670
    • 我认为它更多的是数组和引用。
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 2015-07-11
    • 2013-08-01
    • 2019-09-10
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2011-08-15
    相关资源
    最近更新 更多