PHP- Function arguments

php-function argument-gaurav dixit
Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right.

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists and Named Arguments are also supported.


Example #1 Passing arrays to functions


<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>

Example #2 Function Argument List with trailing Comma


<?php
function takes_many_args(
$first_arg,
$second_arg,
$a_very_long_argument_name,
$arg_with_default = 5,
$again = 'a default string', // This trailing comma was not permitted before 8.0.0.
)
{
// ...
}
?>

Example #3 Passing optional arguments after mandatory arguments


<?php
function foo($a = [], $b) {} // Before
function foo($a, $b) {} // After

function bar(A $a = null, $b) {} // Still allowed
function bar(?A $a, $b) {} // Recommended
?>

Post a Comment

Previous Post Next Post