search for in the  
<FunctionsReturning values>
Last updated: Thu, 19 May 2005

Function arguments

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

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are supported only in PHP 4 and later; see Variable-length argument lists and the function references for func_num_args(), func_get_arg(), and func_get_args() for more information. A similar effect can be achieved in PHP 3 by passing an array of arguments to a function:

Example 17-5. Passing arrays to functions

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

Making arguments be passed by reference

By default, function arguments are passed by value (so that if you change the value of the argument within the function, it does not get changed outside of the function). If you wish to allow a function to modify its arguments, you must pass them by reference.

If you want an argument to a function to always be passed by reference, you can prepend an ampersand (&) to the argument name in the function definition:

Example 17-6. Passing function parameters by reference

<?php
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.'
?>

Default argument values

A function may define C++-style default values for scalar arguments as follows:

Example 17-7. Use of default parameters in functions

<?php
function makecoffee($type = "cappuccino")
{
   return
"Making a cup of $type.\n";
}
echo
makecoffee();
echo
makecoffee("espresso");
?>

The output from the above snippet is:

Making a cup of cappuccino.
Making a cup of espresso.

Also PHP allows you to use arrays and special type NULL as default values, for example:

Example 17-8. Using non-scalar types as default values

<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
  
$device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
   return
"Making a cup of ".join(", ", $types)." with $device.\n";
}
echo
makecoffee();
echo
makecoffee(array("cappuccino", "lavazza"), "teapot");
?>

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet:

Example 17-9. Incorrect usage of default function arguments

<?php
function makeyogurt($type = "acidophilus", $flavour)
{
   return
"Making a bowl of $type $flavour.\n";
}
 
echo
makeyogurt("raspberry");  // won't work as expected
?>

The output of the above example is:

Warning: Missing argument 2 in call to makeyogurt() in 
/usr/local/etc/httpd/htdocs/php3test/functest.html on line 41
Making a bowl of raspberry .

Now, compare the above with this:

Example 17-10. Correct usage of default function arguments

<?php
function makeyogurt($flavour, $type = "acidophilus")
{
   return
"Making a bowl of $type $flavour.\n";
}
 
echo
makeyogurt("raspberry");  // works as expected
?>

The output of this example is:

Making a bowl of acidophilus raspberry.

Note: As of PHP 5, default values may be passed by reference.

Variable-length argument lists

PHP 4 and above has support for variable-length argument lists in user-defined functions. This is really quite easy, using the func_num_args(), func_get_arg(), and func_get_args() functions.

No special syntax is required, and argument lists may still be explicitly provided with function definitions and will behave as normal.



User Contributed Notes
Function arguments
csaba at alum dot mit dot edu
26-Jan-2005 07:58
Argument evaluation left to right means that you can save yourself a temporary variable in the example below whereas $current = $prior + ($prior=$current) is just the same as $current *= 2;

function Sum() { return array_sum(func_get_args()); }
function Fib($n,$current=1,$prior=0) {
   for (;--$n;) $current = Sum($prior,$prior=$current);
   return $current;
}

Csaba Gabor
PS.  You could, of course, just use array_sum(array(...)) in place of Sum(...)
trosos at atlas dot cz
15-Jul-2004 09:31
Function arguments are evaluated from left to right.
heck AT fas DOT harvard DOT edu
24-Mar-2004 08:49
I have some functions that I'd like to be able to pass arguments two ways: Either as an argument list of variable length (e.g. func(1, 2, 3, 4)) or as an array (e.g., func(array(1,2,3,4)). Only the latter can be constructed on the fly (e.g., func($ar)), but the syntax of the former can be neater.

The way to do it is to begin the function as follows:
  $args = func_get_args();
  if (is_array ($args[0]))
   $args = $args[0];
Then one can just use $args as the list of arguments.
thesibster at hotmail dot com
30-Jun-2003 02:43
Call-time pass-by-ref arguments are deprecated and may not be supported later, so doing this:

----
function foo($str) {
   $str = "bar";
}

$mystr = "hello world";
foo(&$mystr);
----

will produce a warning when using the recommended php.ini file.  The way I ended up using for optional pass-by-ref args is to just pass an unused variable when you don't want to use the resulting parameter value:

----
function foo(&$str) {
   $str = "bar";
}

foo($_unused_);
----

Note that trying to pass a value of NULL will produce an error.
bishop
03-Jun-2003 05:06
A tiny clarification on the notes of "keeper at odi dot com dot br", et. al.

Functions explicitly prototyped with formal parameters passed by reference can't have default values. However, functions prototyped to assign default values to formal parameters may be passed references.

For example, this is a parse error:

function foo(&$bar = null) {
   // formal parameters as references can't have default values
   $bar = 242;
}

While this is perfectly legal (and probably what you want, mostly):

function foo($bar = null) {
   $bar = 242;
}

foo();    // valid call, no warnings about missing args
foo(&$x); // valid call, post $x == 242
mjohnston at planetactive dot com
26-Mar-2003 10:14
not only do default values not work with passing by reference, but you can't pass NULL as a parameter that is expected to be a reference, and passing too few parameters to a function causes a warning.
bostjan dot skufca at domenca dot com
09-Dec-2002 07:16
have function

function foo($bar=3) {
  if (!isset($bar)) {
   echo "I'm not set to my default value";
}

and if you do

foo($some_unset_variable);

the $bar variable does not adopt default value (3) as one might expect but it is not set.
guillaume dot goutaudier at eurecom dot fr
19-Jul-2002 03:15
Concerning default values for arguments passed by reference:
I often use that trick:
func($ref=$defaultValue) {
   $ref = "new value";
}
func(&$var);
print($var) // echo "new value"

Setting $defaultValue to null enables you to write functions with optional arguments which, if given, are to be modified.
t dot orf at gmx dot de
07-May-2002 09:48
concerning rbronosky@mac.com 11-May-2001 06:17:
You can include the variable name in the output if you simply pass that name instead of the value:

function show($arrayName) {
  global $$arrayName;
  echo("<pre>\n$arrayName == ");
  print_r($$arrayName);
  echo "</pre>";
}

show('myArray');
wls at wwco dot com
20-Nov-2001 02:29
Follow up to resource passing:

It appears that if you have defined the resource in the same file
as the function that uses it, you can get away with the global trick.

Here's the failure case:

  include "functions_doing_globals.php"
  $conn = openDatabaseConnection();
  invoke_function_doing_global_conn();

...that it fails.

Perhaps it's some strange scoping problem with include/require, or
globals trying to resolve before the variable is defined, rather
than at function execution.
keeper at odi dot com dot br
07-Oct-2001 07:20
Whem arguments are passed by reference, default values won´t work.
duncanmadcow at hotmail dot com
05-Sep-2001 06:50
I have tried the example given by ak@avatartech.com
it did not work I use php 4.0.6 on windows 98

I do think that it is good that there is no automatic parameter passing, thus it would force people to do good programming practie
rwillmann at nocomment dot sk
21-Jun-2001 06:05
There is no way how to deal with calling by reference when variable lengths argument list are passed.
<br>Only solutions is to use construction like this:<br>
function foo($args) {<br>
   ...
}

foo(array(&$first, &$second));

Above example pass by value a list of references to other variables :-)

It is courios, becouse when you call a function with arguments passed via &$parameter syntax, func_get_args returns array of copies :-(

rwi
korba at korbs dot pl
29-May-2001 09:08
Don't try to pass func_get_arg() as an argument of the other function. So:
function foo() {
 foo2(func_get_arg(0));
}
won't work.
artiebob at go dot com
25-Feb-2001 04:48
here is the code to pass a user defined function as an argument.  Just like in the usort method.

func2("func1");
function func1 ($arg){
       print ("Hello $arg");       
}
function func2 ($arg1){       
       $arg1("World");  //Does the same thing as the next line
       call_user_func ($arg1, "World");
}
david at petshelter dot net
25-Jan-2001 02:23
With reference to the note about extract() by dietricha@subpop.com:

He is correct and this is great!  What he does not say explicitly is that the extracted variable names have the scope of the function, not the global namespace.  (This is the appropriate behavior IMO.)  If for some reason you want the extracted variables to be visible in the global namespace, you must declare them 'global' inside the function.
alex at networkessence dot com
24-Jan-2001 05:28
I found this useful:

You can call a function by using the value of a string.

function test() {
   echo "hello world";
   }

$string = "test";

$string();


would output "hello world"
marvinalone at gmx dot net
06-Jan-2001 09:19
Nice to know is this:

If you call a function giving an unset variable, it will be unset in the function. Consider this:

function my_test ($var) {
   if (isset ($var)) echo ("set");
}

my_test ($unused);

This will _not_ echo "set", regardless of the variable being passed by value or by reference.

(If my newlines are messed up, sorry, this seems to be a konqueror problem)
dietricha at subpop dot com
10-Oct-2000 04:39
if you compiled with "--enable-track-vars" then an easy way to get variable function args is to use extract().

$args = array("color" = "blue","number" = 3);

function my_func($args){
extract($args);
echo $color;
echo $number;
}

the above strategy makes it real easy to globalize form data within functions, or to pass form data arrays to functions:

<input type="text" name="test[color]" value="blue">
etc, etc.
Then in your function, pass $test to extract() to turn the array data into global vars.

 or

function my_func($HTTP_POST_VARS){
 extract($HTTP_POST_VARS);
 // use all your vars by name!
  }
coop at better-mouse-trap dot com
09-Oct-2000 11:59
If you prefer to use named arguments to your functions (so you don't have to worry about the order of variable argument lists), you can do so PERL style with anonymous arrays:

function foo($args)
{
   print "named_arg1 : " . $args["named_arg1"] . "\n";
   print "named_arg2 : " . $args["named_arg2"] . "\n";
}

foo(array("named_arg1" => "arg1_value", "named_arg2" => "arg2_value"));


====== will output: =======

named_arg1 : arg1_value
named_arg2 : arg2_value
almasy at axisdata dot com
20-Aug-2000 07:11
Re: Passing By Reference Inside A Class

Passing arguments by reference does work inside a class.  When you do:

   $this->testVar = $ref;

inside setTestVar(), you're copying by value instead of copying by reference.  I think what you want there is this:

   $this->testVar = &$ref;

Which is the new "assign by reference" syntax that was added in PHP4.
dmb27 at cornell dot edu
13-Jul-2000 12:50
The first comment should use func_get_arg(0) and func_get_arg(1) to refer to the 2 parameters (and not func_get_arg(2) ).  func_get_arg() starts counting at 0, so the first parameter is func_get_arg(0) and the second is func_get_arg(1)
ak at avatartech dot com
24-Apr-2000 01:19
One interesting thing I've noticed:

function foo() {  // accepts any number of arguments
  bar()
}

function bar($x,$y) {  // same
  print("$x $y");
}

foo("one","two);

OUPUT: "one two"

That is, PHP will automatically pass all the variables passed to foo() into bar() if you don't pass them explicitly. I'm not sure how far this extends (i.e. if you pass just one variable, will the rest still get tacked on? etc), but it's interesting, and undocumented.
21-Apr-2000 05:45
You may pass any number of extra parameters to a function, regardless of the prototyping. In addition, the arguments passed to a function will be available via the variable names defined in the function prototype, as well as via the func_get_arg() and func_get_args() functions.

For example:
function printme ($arg) {
   for ($ndx = 0; $ndx < $num_args; ++$ndx)
       $output .= func_get_arg ($ndx);

   print $output;
}

printme ("one ", "two"); # This prints "one two".

This behavior is useful for setting default values for function arguments and for ensuring that a certain number of arguments get passed to a function.

<FunctionsReturning values>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 18:35:34 2005 EDT