Function Arguments
In the latest version of PHP there are well over 5000 functions built into the core of PHP these functions range from echoing and printing a string to creating and manipulating files and databases. In this tutorial I will show you how you can create you own functions.
Predefined Function Arguments
A function is often created using predefined arguments for example
<?php
function foo($bar1, $bar2=''){
echo "bar1: " . $bar1 . "\n";
echo "bar2: " . $bar2 . "\n";
}
?>
With this example 2 fields are created with the function $bar1 and $bar2. $bar1 is a required argument that must be entered when calling the function where as $bar2 is set to null by default allowing the argument to optional while calling the function.
On The Fly Function Arguments
Using the function func_get_args(); you can add any number of arguments to the function without first defining them, these can be simply set while calling the actual function.
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
?>
In this example I will also be using the functions func_num_args(); and func_get_arg(); These functions will count the total number of arguments submitted to the function while calling it. The other will get the argument when supplied with the argument number.
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
In this section we start the function with no predefined arguments set we then count the total number of arguments submitted when calling the function using the func_num_args(); we then set this to the variable $numargs. This number is then echoed.
If this number is equal to or larger than 2 we echo the second argument that was submitted to the function. We get this using the func_get_arg(); function.
Using this next section of code we use the function func_get_args(); and loop through the arguments submitted, and echo them all out.
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
?>
This method would be excellent for example when adding up numbers as more numbers could be added as required.
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
?>
Leave a Reply
You must be logged in to post a comment.





