<?php
//Source: https://www.demo2s.com/php/php-function-arguments.html
//Function arguments
echo "Function arguments:\r\n";
function a($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
a(array(1,2));
function a_func(
$first_arg,
$second_arg,
$test,
$arg_with_default = 5,
$again = 'a default string', // This trailing comma was not permitted before 8.0.0.
){
echo "\r\n" . $first_arg . " " . $second_arg . " " . $test . " " . $arg_with_default . " " . $again . "\r\n";
}
a_func("lets","make","number");
//Passing arguments by reference to Function
echo "Passing arguments by reference to Function:\r\n";
function add_some_extra(&$string)
{
$string .= ' end.';
}
$str = 'start, ';
add_some_extra($str);
echo $str . "\r\n";
//User-defined functions
echo "User-defined functions:\r\n";
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example User-defined function.\n";
$x = $arg_1 . " " . $arg_2 . " " . $arg_n . "\r\n";
return $x;
}
echo "Calling foo() here\n";
echo foo(1,2,3);
//Conditional functions
echo "Conditional functions:\r\n";
$makefoo2 = true;
/* We can't call foo2() from here
since it doesn't exist yet,
but we can call bar() */
bar();
if ($makefoo2) { //Set to true earlier.
echo "Making foo2 function here\n";
function foo2()
{
echo "I don't exist until program execution reaches me.\n";
}
}
/* Now we can safely call foo2()
since $makefoo2 evaluated to true */
if ($makefoo2) {foo2();} //If makefoo2 is true, call foo2.
function bar()
{
echo "Inside bar() function here\n";
echo "I exist immediately upon program start.\n";
}
//Functions within functions
echo "Functions within functions:\r\n";
function foo3()
{
echo "Creating bar2() function here\n";
function bar2()
{
echo "I don't exist until foo3() is called.\n";
}
}
/* We can't call bar2() yet since it doesn't exist. */
foo3();
/* Now we can call bar2(), foo3()'s processing has made it accessible. */
bar2();
/*All functions and classes in PHP have the global scope.
All functions and classes can be called outside a function even if they were defined inside and vice versa.
PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.
Function names are case-insensitive for the ASCII characters A to Z.
Both variable number of arguments and default arguments are supported in functions.
It is possible to call recursive functions in PHP.*/
//Recursive functions
echo "Recursive functions:\r\n";
function recursion($a)
{
if ($a <= 20) {
echo "$a.\n";
recursion($a + 1);
}
}
recursion(14); //Passing 14 to recursion();
?>