简体   繁体   English

在PHP中通过引用传递(函数定义和变量)

[英]Passing by reference in PHP (function definition and variables)

What's the difference between function &foo() and function foo(&$var) in PHP? PHP中的函数&foo()和函数foo(&$ var)有什么区别?

Example in code: 代码示例:

<?php
function foo(&$var){
   $var++;
}

function &bar(){
   $a= 5;
   return $a;
}

foo( bar() );

The main issue here is who wants to alter or read whose variable. 这里的主要问题是谁想要更改或读取谁的变量。 In the first example you want the outer variable to be changed by the function. 在第一个示例中,您希望外部变量由函数更改。 In example two you want the outer world to change the inner variable. 在示例二中,您希望外部世界更改内部变量。 And you can get changed values from the different scope. 您可以从其他范围获得更改的值。

A better use case for the second version would be: 第二个版本的更好用例是:

class example {
    public $test = 23;

    public function &exposeTest() {
        return $this->test;
    }
}

$example1 = new example;
$testref = &$example1->exposeTest();
$testref++;
echo($example1->test); // 24
$example1->test++;
echo($testref); // 25

So it is not really a difference besides design issues and without OOP may not matter any way. 因此,除了设计问题外,这没有什么区别,没有OOP可能没有任何关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM