Pass by Reference

When parameters are passed in to a function by value, PHP takes a copy of the value and uses the copy within the function, leaving the original unchanged  outside the function.

 

In order to change the original value, it must be passed in by reference (as per assigning a variable by reference) so that the actual variable is passed in to the function.

 

function functionName( &$argument){

statements ;

}

 

Therefore any changes to that variable within the function will be reflected outside the function.

 

<?php

    function myFunction(&$myArg) { //passing in the argument by reference - note use of &

		echo "Hello, $myArg <br>" ;

		$myArg = " Good to see you!" ; //re-assigning the passed in referenced variable
    }

	$myVar = "World!" ;

    myFunction($myVar) ;

	echo "\$myVar was re-assigned in the function to: $myVar" ;
?>

Displays:

Hello, World!
$myVar was re-assigned in the function to: Good to see you!

Leave a Reply