PHP Tutorial PHP Advanced PHP References

PHP Functions - Pass by Value



When the argument or parameter of a function is passed by value, then the function takes only the value of parameter and any changes made to the parameter inside the function have no effect on the parameter. By default, PHP uses pass by value method which means that code within a function will not change the parameter used to pass in the function.

Example:

In the example below, the function called Square is created which returns square of the passed argument. The function modify the parameter as square of itself before returning it. In the PHP script, when the passed argument is printed after calling the function Square, the value of the parameter remains unaffected because it was passed by value.

<?php 
function Square($x){
  $x = $x*$x;
  return $x; 
}

$x = 5;
echo "Initial value of x: $x\n";
Square($x); 
echo "Value of x, after passed by value: $x\n";
?>

The output of the above code will be:

Initial value of x: 5
Value of x, after passed by value: 5

❮ PHP - Functions

5