Core PHP

Passing Arguments by Reference or Value

This PHP code is an example program that demonstrates how to pass arguments into a function by reference or value.

ArgumentsByReferenceOrValue.php

<?php

// This is a function that passes its argument by value.
// This creates a copy of the passed in value to use inside the function.
function IncrementByValue($iAnInt) {
  ++$iAnInt;
}

// This is a function that passes its argument by reference.
// This uses the actual value that was passed into the function.
function IncrementByReference(&$irAnInt) {
  ++$irAnInt;
}

// The value is initially set to 20.
$iMyInt = 20;
echo "Initial Value = ".$iMyInt."<br />";

// Increment the copied value.
IncrementByValue($iMyInt);
echo "After IncrementByValue() Call = ".$iMyInt."<br />";

// Increment the actual value.
IncrementByReference($iMyInt);
echo "After IncrementByReference() Call = ".$iMyInt."<br />";

?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.