简体   繁体   中英

Passing by reference in PHP (function definition and variables)

What's the difference between function &foo() and function foo(&$var) in PHP?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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