Functions


Function Arguments

PHPoC supports pass by value, pass by reference and default argument values.

<?php

function func($arg1, $arg2)  // pass by value
{
  $temp = $arg1;
  $arg1 = $arg2;
  $arg2 = $temp;
  return $arg1 + 1;
}
$var1 = 1;
$var2 = 2;
func($var1, $var2);          // function call
echo "$var1, $var2";         // $var1 and $var2 are not swapped

?>
[result]  
1, 2
  • Pass by Reference
    If arguments are passed by reference, the memory address of argument is passed instead of value. Thus, if the value of the argument within the function is changed, it gets changed outside of the function. To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition.
<?php

function func(&$arg1, &$arg2)  // pass by reference
{
  $temp = $arg1;
  $arg1 = $arg2;
  $arg2 = $temp;
  return $arg1 + 1;
}
$var1 = 1;
$var2 = 2;
func($var1, $var2);            // function call
echo "$var1, $var2";           // $var1 and $var2 are swapped

?>
[result]  
2, 1
  • Default Argument Values
    A function may define default values for scalar arguments as follows:
<?php

function print_str($str = "Hello PHPoC!\r\n")  // set default argument value
{
  echo $str;
}
print_str();                                   // call print_str() without argument

?>
[result]  
Hello PHPoC!