Oct
08
2008

Functions: Arguments and Reference Arguments

Zend PHP 5 Certification Blog will now refresh our memory about passing arguments to functions, its a small and simple topic until we get to “Passing Arguments by Reference” where it may get confusing.

Define: Function Arguments

Information may be passed to functions via the argument list, which is a comma-delimited list of expressions.

Arguments in Functions:

A function is much like a factory you bring in some materials and it outputs something different. You can pass as many arguments (variables) to a function as you want. Here is a maths function:

function domath($type, $var1, $var2){
if($type == "add"){
return $var1 + $var2;
} else {
return $var1 - $var2;
}
$var1 = 10;
$var2 = 5;
echo domath("add",$var1,$var2); //Outputs 15 (variables are added)
echo domath("other",$var1,$var2); //Outputs 5 (variable is subtracted by 5)

As you can see here we passed three arguments, the first one was the method to add or subtract the choice is static and typed into the function. The two other arguments are variable numbers which are used in the function to return their new value.

Array Arguments in Functions:

We can also pass arrays to functions!

function domath($type, $array){
if($type == "add"){
return $array[0] + $array[1];
} else {
return $array[0] - $array[1];
}
$array[0] = 10;
$array[1] = 5;
echo domath("add",$array); //Outputs 15 (variables are added)
echo domath("other",$array); //Outputs 5 (variable is subtracted by 5)

OMG! Its the same script as above except with arrays, the script gives us the same results as before. Arrays in functions may be very useful, We could have used a loop in the function to add/subtract every value in the array automatically. This way the script could dynamically add more values to the array and the output would be very different

Default Arguments in Functions:

In PHP functions can be assigned a value if you do not use one in calling the function. Its best to jump straight into an example:

function makecup($type = "cappuccino"){
   return "Making a cup of $type\n";
}
echo makecup(); //Outputs "Making a cup of cappuccino"
echo makecup(null); //Outputs "Making a cup of "
echo makecup("espresso"); //Outputs "Making a cup of espresso"

As you can see if no argument is passed then it used the one assigned in the variable “cappuccino” if any other value including NULL is passed as an argument then that is used instead. This is a good capability of PHP Functions, although you must be careful when using this with multiple arguments:

function function_1($type = "language", $language){
   return "$language is a great $type.\n";
}
echo function_1("PHP");  // won't work as expected
 
function function_2($language, $type = "language"){
   return "$language is a great $type.\n";
}
echo function_1("PHP");  // Will return: "PHP is a great Language"
echo function_1("PHP","Code");  // Will return: "PHP is a great Code"

As you can see function_1 arguments are ordered incorrectly this will cause an error! as their is no default value for $language it will output an error.
Whereas function_2 is the same code except the arguments are ordered to that a value is passed to the first argument which has no default value.

Variable-Length Arguments in Functions:

Their are many ways to send data to functions, one that can be useful in complex functions is that PHP allows you to accept a variable number of arguments depending on the circumstance. Their are some built in functions to handle this:
func_num_args() - The total ammount of arguments passed to the function
func_get_arg(0) - The first argument passed to the function
func_get_args() - All The arguments are passed to the function stored in an array.
Here is an example:

<?php
function hello(){
	if((func_num_args() > 1) && (func_num_args() < 3)) {
		$arg = func_get_args();
		echo "Hello $arg[0] and $arg[1]";
	} elseif (func_num_args() > 0) {
		$arg1 = func_get_arg(0);
		echo "Hello $arg1";
	} else {
		echo "Hello World";
	}
}
 
echo hello("England", "USA").'<br>'; //Prints "Hello England and USA"
echo hello("Reader").'<br>'; // Prints "Hello Reader"
echo hello().'<br>'; // Prints "Hello World"
?>
As you can see in the first if I used the array function as their is more than two arguments and output them in the sentence.
The seccond condition is used if one argument is passed one argument, instead of useing the array function I directly requested the first argument (as theris only one) and used it in the sentence.
The last argument is if no arguments are passed, it outputs static text as their are no variables to use.

Passed By Referenced Arguments in Functions:

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition:

function add_some_extra(&$string)
{
   $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'

As you can see this is very useful, passing by reference to me means that their are two names for the same value. What you do to one value effects the other value.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 02. Functions | Tags: , , ,

No Comments »

RSS feed for comments on this post. TrackBack URL

Leave a comment

WordPress Powered, Theme by TheBuckmaker.com | Add to Technorati Favorites. | RSS and Comments RSS