Function arguments

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 are also supported.

Example #1 Passing arrays to functions

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

Passing arguments by reference

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:

Example #2 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 #3 Use of default parameters in functions

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

The above example will output:

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

PHP also allows the use of arrays and the special type NULL as default values, for example:

Example #4 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 #5 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 above example will output:

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

Now, compare the above with this:

Example #6 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 above example will output:

Making a bowl of acidophilus raspberry.

Note: As of PHP 5, arguments that are passed by reference may have a default value.

Type declarations

Note:

Type declarations were also known as type hints in PHP 5.

Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.

To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL values if the default value of the parameter is set to NULL.

Valid types

Type Description Minimum PHP version
Class/interface name The parameter must be an instanceof the given class or interface name. PHP 5.0.0
self The parameter must be an instanceof the same class as the one the method is defined on. This can only be used on class and instance methods. PHP 5.0.0
array The parameter must be an array. PHP 5.1.0
callable The parameter must be a valid callable. PHP 5.4.0
bool The parameter must be a boolean value. PHP 7.0.0
float The parameter must be a floating point number. PHP 7.0.0
int The parameter must be an integer. PHP 7.0.0
string The parameter must be a string. PHP 7.0.0
iterable The parameter must be either an array or an instanceof Traversable. PHP 7.1.0
Warning

Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool:

<?php
 
function test(boolean $param) {}
 
test(true);
 
?>

The above example will output:

 Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given, called in - on line 1 and defined in -:1
 

Examples

Example #7 Basic class type declaration

<?php
class {}
class 
extends {}

// This doesn't extend C.
class {}

function 
f(C $c) {
    echo 
get_class($c)."\n";
}

f(new C);
f(new D);
f(new E);
?>

The above example will output:

C
D

Fatal error: Uncaught TypeError: Argument 1 passed to f() must be an instance of C, instance of E given, called in - on line 14 and defined in -:8
Stack trace:
#0 -(14): f(Object(E))
#1 {main}
  thrown in - on line 8

Example #8 Basic interface type declaration

<?php
interface { public function f(); }
class 
implements { public function f() {} }

// This doesn't implement I.
class {}

function 
f(I $i) {
    echo 
get_class($i)."\n";
}

f(new C);
f(new E);
?>

The above example will output:

C

Fatal error: Uncaught TypeError: Argument 1 passed to f() must implement interface I, instance of E given, called in - on line 13 and defined in -:8
Stack trace:
#0 -(13): f(Object(E))
#1 {main}
  thrown in - on line 8

Example #9 Nullable type declaration

<?php
class {}

function 
f(C $c null) {
    
var_dump($c);
}

f(new C);
f(null);
?>

The above example will output:

object(C)#1 (0) {
}
NULL

Strict typing

By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.

It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float. Function calls from within internal functions will not be affected by the strict_types declaration.

To enable strict mode, the declare statement is used with the strict_types declaration:

Caution

Enabling strict mode will also affect return type declarations.

Note:

Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (weak typing) will be respected, and the value will be coerced.

Note:

Strict typing is only defined for scalar type declarations, and as such, requires PHP 7.0.0 or later, as scalar type declarations were added in that version.

Example #10 Strict typing

<?php
declare(strict_types=1);

function 
sum(int $aint $b) {
    return 
$a $b;
}

var_dump(sum(12));
var_dump(sum(1.52.5));
?>

The above example will output:

int(3)

Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 9 and defined in -:4
Stack trace:
#0 -(9): sum(1.5, 2.5)
#1 {main}
  thrown in - on line 4

Example #11 Weak typing

<?php
function sum(int $aint $b) {
    return 
$a $b;
}

var_dump(sum(12));

// These will be coerced to integers: note the output below!
var_dump(sum(1.52.5));
?>

The above example will output:

int(3)
int(3)

Example #12 Catching TypeError

<?php
declare(strict_types=1);

function 
sum(int $aint $b) {
    return 
$a $b;
}

try {
    
var_dump(sum(12));
    
var_dump(sum(1.52.5));
} catch (
TypeError $e) {
    echo 
'Error: '.$e->getMessage();
}
?>

The above example will output:

int(3)
Error: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 10

Variable-length argument lists

PHP has support for variable-length argument lists in user-defined functions. This is implemented using the ... token in PHP 5.6 and later, and using the func_num_args(), func_get_arg(), and func_get_args() functions in PHP 5.5 and earlier.

... in PHP 5.6+

In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

Example #13 Using ... to access variable arguments

<?php
function sum(...$numbers) {
    
$acc 0;
    foreach (
$numbers as $n) {
        
$acc += $n;
    }
    return 
$acc;
}

echo 
sum(1234);
?>

The above example will output:

10

You can also use ... when calling functions to unpack an array or Traversable variable or literal into the argument list:

Example #14 Using ... to provide arguments

<?php
function add($a$b) {
    return 
$a $b;
}

echo 
add(...[12])."\n";

$a = [12];
echo 
add(...$a);
?>

The above example will output:

3
3

You may specify normal positional arguments before the ... token. In this case, only the trailing arguments that don't match a positional argument will be added to the array generated by ....

It is also possible to add a type hint before the ... token. If this is present, then all arguments captured by ... must be objects of the hinted class.

Example #15 Type hinted variable arguments

<?php
function total_intervals($unitDateInterval ...$intervals) {
    
$time 0;
    foreach (
$intervals as $interval) {
        
$time += $interval->$unit;
    }
    return 
$time;
}

$a = new DateInterval('P1D');
$b = new DateInterval('P2D');
echo 
total_intervals('d'$a$b).' days';

// This will fail, since null isn't a DateInterval object.
echo total_intervals('d'null);
?>

The above example will output:

3 days
Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2

Finally, you may also pass variable arguments by reference by prefixing the ... with an ampersand (&).

Older versions of PHP

No special syntax is required to note that a function is variadic; however access to the function's arguments must use func_num_args(), func_get_arg() and func_get_args().

The first example above would be implemented as follows in PHP 5.5 and earlier:

Example #16 Accessing variable arguments in PHP 5.5 and earlier

<?php
function sum() {
    
$acc 0;
    foreach (
func_get_args() as $n) {
        
$acc += $n;
    }
    return 
$acc;
}

echo 
sum(1234);
?>

The above example will output:

10

add a note add a note

User Contributed Notes 43 notes

up
50
php at richardneill dot org
2 years ago
To experiment on performance of pass-by-reference and pass-by-value, I used this  script. Conclusions are below.

#!/usr/bin/php
<?php
function sum($array,$max){   //For Reference, use:  "&$array"
   
$sum=0;
    for (
$i=0; $i<2; $i++){
       
#$array[$i]++;        //Uncomment this line to modify the array within the function.
       
$sum += $array[$i]; 
    }
    return (
$sum);
}

$max = 1E7                  //10 M data points.
$data = range(0,$max,1);

$start = microtime(true);
for (
$x = 0 ; $x < 100; $x++){
   
$sum = sum($data, $max);
}
$end microtime(true);
echo
"Time: ".($end - $start)." s\n";

/* Run times:
#    PASS BY    MODIFIED?   Time
-    -------    ---------   ----
1    value      no          56 us
2    reference  no          58 us

3    valuue     yes         129 s
4    reference  yes         66 us

Conclusions:

1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
   only copied on write. That's why  #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
   [You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]

2. You do use &$array  to tell the compiler "it is OK for the function to over-write my argument in place, I don't need the original
   any more." This can make a huge difference to performance when we have large amounts of memory to copy.
   (This is the only way it is done in C, arrays are always passed as pointers)

3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
   (This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
   in an array)

4. It's  unhelpful that only the function definition has &. The caller should have it, at least as syntactic sugar. Otherwise
   it leads to unreadable code: because the person reading the function call doesn't expect it to pass by reference. At the moment,
   it's necessary to write a by-reference function call with a comment, thus:
    $sum = sum($data,$max);  //warning, $data passed by reference, and may be modified.

5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn't allow it, but it
   would be meaningful for the caller to decide to pass data in as a reference. i.e. "I'm done with the variable, it's OK to stomp
   on it in memory".
*/
?>
up
18
gabriel at figdice dot org
1 year ago
A function's argument that is an object, will have its properties modified by the function although you don't need to pass it by reference.

<?php
$x
= new stdClass();
$x->prop = 1;

function
f ( $o ) // Notice the absence of &
{
 
$o->prop ++;
}

f($x);

echo
$x->prop; // shows: 2
?>

This is different for arrays:

<?php
$y
= [ 'prop' => 1 ];

function
g( $a )
{
 
$a['prop'] ++;
  echo
$a['prop'];  // shows: 2
}

g($y);

echo
$y['prop'];  // shows: 1
?>
up
21
carlos at wfmh dot org dot pl dot REMOVE dot COM
7 years ago
You can use (very) limited signatures for your functions, specifing type of arguments allowed.

For example:

public function Right( My_Class $a, array $b )

tells first argument have to by object of My_Class, second an array. My_Class means that you can pass also object of class that either extends My_Class or implements (if My_Class is abstract class) My_Class. If you need exactly My_Class you need to either make it final, or add some code to check what $a really.

Also note, that (unfortunately) "array" is the only built-in type you can use in signature. Any other types i.e.:

public function Wrong( string $a, boolean $b )

will cause an error, because PHP will complain that $a is not an *object* of class string (and $b is not an object of class boolean).

So if you need to know if $a is a string or $b bool, you need to write some code in your function body and i.e. throw exception if you detect type mismatch (or you can try to cast if it's doable).
up
13
Sergio Santana: ssantana at tlaloc dot imta dot mx
12 years ago
PASSING A "VARIABLE-LENGTH ARGUMENT LIST OF REFERENCES" TO A FUNCTION
As of PHP 5, Call-time pass-by-reference has been deprecated, this represents no problem in most cases, since instead of calling a function like this:
   myfunction($arg1, &$arg2, &$arg3);

you can call it
   myfunction($arg1, $arg2, $arg3);

provided you have defined your function as
   function myfuncion($a1, &$a2, &$a3) { // so &$a2 and &$a3 are
                                                             // declared to be refs.
    ... <function-code>
   }

However, what happens if you wanted to pass an undefined number of references, i.e., something like:
   myfunction(&$arg1, &$arg2, ..., &$arg-n);?
This doesn't work in PHP 5 anymore.

In the following code I tried to amend this by using the
array() language-construct as the actual argument in the
call to the function.

<?php

 
function aa ($A) {
   
// This function increments each
    // "pseudo-argument" by 2s
   
foreach ($A as &$x) {
     
$x += 2;
    }
  }

 
$x = 1; $y = 2; $z = 3;
 
 
aa(array(&$x, &$y, &$z));
  echo
"--$x--$y--$z--\n";
 
// This will output:
  // --3--4--5--
?>

I hope this is useful.

Sergio.
up
8
Horst Schirmeier
3 years ago
Editor's note: what is expected here by the parser is a non-evaluated expression. An operand and two constants requires evaluation, which is not done by the parser. However, this feature is included as of PHP 5.6.0. See this page for more information: http://php.net/migration56.new-features#migration56.new-features.const-scalar-exprs
--------

"The default value must be a constant expression" is misleading (or even wrong).  PHP 5.4.4 fails to parse this function definition:

function htmlspecialchars_latin1($s, $flags = ENT_COMPAT | ENT_HTML401) {}

This yields a " PHP Parse error:  syntax error, unexpected '|', expecting ')' " although ENT_COMPAT|ENT_HTML401 is certainly what a compiler-affine person would call a "constant expression".

The obvious workaround is to use a single special value ($flags = NULL) as the default, and to set it to the desired value in the function's body (if ($flags === NULL) { $flags = ENT_COMPAT | ENT_HTML401; }).
up
6
jcaplan at bogus dot amazon dot com
11 years ago
In function calls, PHP clearly distinguishes between missing arguments and present but empty arguments.  Thus:

<?php
function f( $x = 4 ) { echo $x . "\\n"; }
f(); // prints 4
f( null ); // prints blank line
f( $y ); // $y undefined, prints blank line
?>

The utility of the optional argument feature is thus somewhat diminished.  Suppose you want to call the function f many times from function g, allowing the caller of g to specify if f should be called with a specific value or with its default value:

<?php
function f( $x = 4 ) {echo $x . "\\n"; }

// option 1: cut and paste the default value from f's interface into g's
function g( $x = 4 ) { f( $x ); f( $x ); }

// option 2: branch based on input to g
function g( $x = null ) { if ( !isset( $x ) ) { f(); f() } else { f( $x ); f( $x ); } }
?>

Both options suck.

The best approach, it seems to me, is to always use a sentinel like null as the default value of an optional argument.  This way, callers like g and g's clients have many options, and furthermore, callers always know how to omit arguments so they can omit one in the middle of the parameter list.

<?php
function f( $x = null ) { if ( !isset( $x ) ) $x = 4; echo $x . "\\n"; }

function
g( $x = null ) { f( $x ); f( $x ); }

f(); // prints 4
f( null ); // prints 4
f( $y ); // $y undefined, prints 4
g(); // prints 4 twice
g( null ); // prints 4 twice
g( 5 ); // prints 5 twice

?>
up
9
herenvardoREMOVEatSTUFFgmailINdotCAPScom
8 years ago
There is a nice trick to emulate variables/function calls/etc as default values:

<?php
$myVar
= "Using a variable as a default value!";

function
myFunction($myArgument=null) {
    if(
$myArgument===null)
       
$myArgument = $GLOBALS["myVar"];
    echo
$myArgument;
}

// Outputs "Hello World!":
myFunction("Hello World!");
// Outputs "Using a variable as a default value!":
myFunction();
// Outputs the same again:
myFunction(null);
// Outputs "Changing the variable affects the function!":
$myVar = "Changing the variable affects the function!";
myFunction();
?>
In general, you define the default value as null (or whatever constant you like), and then check for that value at the start of the function, computing the actual default if needed, before using the argument for actual work.
Building upon this, it's also easy to provide fallback behaviors when the argument given is not valid: simply put a default that is known to be invalid in the prototype, and then check for general validity instead of a specific value: if the argument is not valid (either not given, so the default is used, or an invalid value was given), the function computes a (valid) default to use.
up
6
conciseusa at yahoo[nospammm] dot com
10 years ago
With regards to:

It is also possible to force a parameter type using this syntax. I couldn't see it in the documentation.
function foo(myclass par) { }

I think you are referring to Type Hinting. It is documented here: http://ch2.php.net/language.oop5.typehinting
up
5
John
11 years ago
This might be documented somewhere OR obvious to most, but when passing an argument by reference (as of PHP 5.04) you can assign a value to an argument variable in the function call. For example:

function my_function($arg1, &$arg2) {
  if ($arg1 == true) {
    $arg2 = true;
  }
}
my_function(true, $arg2 = false);
echo $arg2;

outputs 1 (true)

my_function(false, $arg2 = false);
echo $arg2;

outputs 0 (false)
up
2
mracky at pacbell dot net
7 years ago
Nothing was written here about argument types as part of the function definition.

When working with classes, the class name can be used as argument type.  This acts as a reminder to the user of the class, as well as a prototype for php  control. (At least in php 5 -- did not check 4).

<?php
class foo {
  public
$data;
  public function
__construct($dd)
  {
   
$this->data = $dd;
  }
};

class
test {
  public
$bar;

  public function
__construct(foo $arg) // Strict typing for argument
 
{
   
$this->bar = $arg;
  }
  public function
dump()
  {
    echo
$this->bar->data . "\n";
  }

};

$A = new foo(25);
$Test1 = new test($A);
$Test1->dump();
$Test2 = new test(10); // wrong argument for testing

?>
outputs:
25
PHP Fatal error:  Argument 1 passed to test::__construct() must be an object of class foo, called in testArgType.php on line 27 and defined in testArgType.php on line 13
up
2
ksamvel at gmail dot com
11 years ago
by default Classes constructor does not have any arguments. Using small trick with func_get_args() and other relative functions constructor becomes a function w/ args (tested in php 5.1.2). Check it out:

class A {
    public function __construct() {
        echo func_num_args() . "<br>";
        var_dump( func_get_args());
        echo "<br>";
    }
}

$oA = new A();
$oA = new A( 1, 2, 3, "txt");

Output:

0
array(0) { }
4
array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> string(3) "txt" }
up
2
allankelly at gmail dot com
8 years ago
I like to pass an associative array as an argument. This is reminiscent of a Perl technique and can be tested with is_array. For example:
<?php
function div( $opt )
{
   
$class = '';
   
$text  = '';
    if(
is_array( $opt ) )
    {
        foreach(
$opt as $k => $v )
        {
            switch(
$k )
            {
                case
'class': $class = "class = '$v'";
                                 break;
                case
'text': $text = $v;
                                 break;
            }
        }
    }
    else
    {
       
$text = $opt;
    }
    return
"<div $class>$text</div>";
}
?>
up
2
info at keraweb dot nl
2 months ago
You can use a class constant as a default parameter.

<?php

class A {
    const
FOO = 'default';
    function
bar( $val = self::FOO ) {
        echo
$val;
    }
}

$a = new A();
$a->bar(); // Will echo "default"
up
1
Hayley Watson
3 months ago
There are fewer restrictions on using ... to supply multiple arguments to a function call than there are on using it to declare a variadic parameter in the function declaration. In particular, it can be used more than once to unpack arguments, provided that all such uses come after any positional arguments.

<?php

$array1
= [[1],[2],[3]];
$array2 = [4];
$array3 = [[5],[6],[7]];

$result = array_merge(...$array1); // Legal, of course: $result == [1,2,3];
$result = array_merge($array2, ...$array1); // $result == [4,1,2,3]
$result = array_merge(...$array1, $array2); // Fatal error: Cannot use positional argument after argument unpacking.
$result = array_merge(...$array1, ...$array3); // Legal! $result == [1,2,3,5,6,7]
?>

The Right Thing for the error case above would be for $result==[1,2,3,4], but this isn't yet (v7.1.8) supported.
up
0
catman at esteticas dot se
1 year ago
I wondered if variable length argument lists and references works together, and what the syntax might be. It is not mentioned explicitly yet in the php manual as far as I can find. But other sources mention the following syntax "&...$variable" that works in php  5.6.16.

<?php
function foo(&...$args)
{
   
$i = 0;
    foreach (
$args as &$arg) {
       
$arg = ++$i;
    }
}
foo($a, $b, $c);
echo
'a = ', $a, ', b = ', $b, ', c = ', $c;
?>
Gives
a = 1, b = 2, c = 3
up
-1
Hayley Watson
3 months ago
If you use ... in a function's parameter list, you can use it only once for obvious reasons. Less obvious is that it has to be on the LAST parameter; as the manual puts it: "You may specify normal positional arguments BEFORE the ... token. (emphasis mine).

<?php
function variadic($first, ...$most, $last)
{
/*etc.*/}

variadic(1, 2, 3, 4, 5);
?>
results in a fatal error, even though it looks like the Thing To Do™ would be to set $first to 1, $most to [2, 3, 4], and $last to 5.
up
-1
g dot sokol99 at g-sokol dot info
10 months ago
Nullable arguments:

<?php

class C {}

function
foo(?C $a)
{
   
var_dump($a);
}

foo(null);

foo();
?>

Output:

NULL
PHP Warning:  Uncaught ArgumentCountError: Too few arguments to function foo(), 0 passed in php shell code on line 1 and exactly 1 expected in php shell code:1
Stack trace:
#0 php shell code(1): foo()
#1 {main}
  thrown in php shell code on line 1

Usage of "?" Is also possible with "string", "int", "array" and so on primitive types (which is strange). Also unliKe "= null" "?" can be passed not only for tail of arguments, e.g.:
<?php
function foo(?string $a, string $b) {}
?>
up
0
pigiman at gmail dot com
7 years ago
Hey,

I started to learn for the Zend Certificate exam a few days ago and I got stuck with one unanswered-well question.
This is the question:
“Absent any actual need for choosing one method over the other, does passing arrays by value to a read-only function reduce performance compared to passing them by reference?’

This question answered by Zend support team at Zend.com:

"A copy of the original $array is created within the function scope. Once the function terminates, the scope is removed and the copy of $array with it." (By massimilianoc)

Have a nice day!

Shaked KO
up
0
Don dot hosek at gmail dot com
10 years ago
Actually the use of class or global constants does buy us something. It helps enforce the DRY (don't repeat yourself) principle.
up
0
nate at natemurray dot com
12 years ago
Of course you can fake a global variable for a default argument by something like this:
<?php
function self_url($text, $page, $per_page = NULL) {
 
$per_page = ($per_page == NULL) ? $GLOBALS['gPER_PAGE'] : $per_page; # setup a default value of per page
 
return sprintf("<a href=%s?page=%s&perpage=%s>%s</a>", $_SERVER["PHP_SELF"], $page, $per_page, $text);
}
?>
up
-1
rburnap at intelligent dash imaging dot com
7 years ago
This may be helpful when you need to call an arbitrary function known only at runtime:

You can call a function as a variable name.
<?php

function foo(){
    echo
"\nfoo()";
}

function
callfunc($x, $y = '')
{
    if(
$y=='' )
    {
        if(
$x=='' )
             echo
"\nempty";
        else
$x();
    }
    else
        
$y->$x();
}

class
cbar {
    public function
fcatch(){ echo "\nfcatch"; }
}

$x = '';
callfunc($x);
$x = 'foo';
callfunc($x);
$o = new cbar();
$x = 'fcatch';
callfunc($x, $o);
echo
"\n\n";
?>

The code will output

empty
foo()
fcatch
up
-1
wls at wwco dot com
16 years ago
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.
up
-1
lucas dot ekrause at gmail dot com
3 years ago
In addition to jcaplan@bogus.amazon.com’s comment (http://www.php.net/manual/de/functions.arguments.php#62803) you could also simply write
<?php
function f($x=4){echo $x."\n";}
function
g($x=null){for($i=0; $i<2; $i++){call_user_func_array("f", !is_null($x) ? array($x) : array());}}
?>
up
-2
aasasdasdf at yandex dot ru
3 years ago
As of PHP 5.5.10, it seems that a variable will be separated from its value if defined right in a function call:

php > error_reporting(E_ALL);
php > function a(&$b) {$b = 1;}
php > a($q = 2); var_dump($q);
Strict Standards: Only variables should be passed by reference in php shell code on line 1
int(2)
php > $w = 3; a($w); var_dump($w);
int(1)

Notice that it's still fine to use a variable that is not defined at all:

php > a($e); var_dump($e);
int(1)
up
down
-2
thesibster at hotma7051ode>om ¶1/a>
1051odesago
Noto tihliza read-irgt; a($q = g p syirglass="keywordsclphpcmym90" rfaceswos sepaa read-on
"\nfcauments.php#62803
) you could alsoomething like this:
<?php
, !is_null($x, is_null<$x, is_null, $x= ) {
  &pan>($x= ) {
  &><$x= ) {
  &an>, $a, !$array3e errlass="ho resos o(), 0 p, diss="copinpyword1,ass="deyword2,ass="deyword3andefault">$a
, !$x=is_null=is_null=$array3e err for oblicitlhle leass=diss="c ',ass="de,'eal originat; a($q = eass=ta
pan>eyword Cannot use positional argument aftepan class="keyword">;It apco> pan>eisump($q);ode"> 8"> "\nfcauments.php#62803) you could alsong like this:
<?php
, !
is_null($x, is_null<$x, is_null, $x=NULL(is_null, !is_null($x, self(NULL<is_null, !is_null, $x, self, NULL, is_null, !is_null, ...$x= self, ...) {
  &pan>() {
  &><) {
  &an>, $array3;
eclasnstion. 10, it r />Nos>
$x
) : array());}}
up
<897dd="Vu79326"> sernotes-voteu">up <897dd="Vu79326"> down
-2
thesibster at hotma897de>
¶;
sago
St"$w); d>PHP Warning:&uy ur />
,
ernotes-voteu">up
down
this..."> -2
wls at wwc156de>
1a56de>eago
Just< ) you cou ld alsncti><call_user_func_array[<?php
();
foo=n clsfault">call_user_func_arrayfoo[<?php
();
foo(();
    }
&nbals.php"
foo(call_user_func_array[$array3D="htr />It apan fakif you n:29ablesbals.php"
foo
();
foo([$x) : array());}}
up
up
-2
lucas dot ekrause at gmail26d="3
Strictass="rbitra;No wat sssitional arguI had ant fgramotisigncode>#0 lt">dir, 0orielass="subdir, 0orielass="ned rir for obto>; aar_duars. Sl oris=">Strictsitional arguInequesspot the synt fgram, I didants>y ing ue of p, so I justtode>Strict,/>y "hit cupcboth>to90"oping pginaIt apphysi> fe symeto co rge. />e>"\nfcauments.php#62803) you could alssweep/lass="keyword">();
foo(foo(cbar />if defstbccur hng ld alsoomething like this:
<?php
();
foo(foo==NULL();
(foo===$o'gPER_PAGE'duarc />'gPER_PAGE'bytrc /><[$array3i>n cls lFuarslap02p - Slzelap02p"oomething like this:
$x) : array());}}
?>
<828="3
up
up
-2
lucas dot ekrause at gmail828="3
la828="3eago
"You acla syntaxsitional arguments BEFORE the ... token. (emphasiass="default">$acla >==span class="default">$x, iSERVER, iSERVER= 'gPER_PAGE'an>==();
foo(&...<>) {
  an>=$xass="keyword">;"\nfc, "arce in th;itional arguments BEFORE the ... token. (emphasiass="default">$acla >==span class="default">$x, iSERVER= 'gPER_PAGE'an>==();
(call_user_func_array,
foo(&...<>) {
  an>=$xass="keyword">;ing like this:
<?php
();
foo(foo<
foo(&...''
class="default">$o= foo
n cl_n class="keyword">= new >foo(&...foon cl_n class="keyword">= new >foo(&...clas">'' class="default">$o= $x<?php
();
foo(foo<$x, is_null=is_null(&...<cbarass="keyword">;"You acla r />Nosbe for $ in8"> ?> 2349de>
ernotes-voteu">up -2 goutaudi33559"eu /ass"> frrong class="user">lucas dot ekrause at gma2349de> ¶5/a>
2349de>e class="ong>
Strict:l arguI often);< sick:the glss="($at g$lass="kVword>$ ho>= "n cl(;va"t //> clas"than at function execution. 356="3
up
-2
skrong class="user">lucas dot ekrause at gmai356="3
1356="3e ago
&n bals.ph} the global tr8)ction();
&Above ex &gl tmp($eStrictt so licitlt; a($q = :-)ion();
&It tod331"ios,e"hno/diclphpcode"rary function kncode adP Warninmp($q);viasp >tode>&rlaay());}}
?>
<7882"3
up
up
-2
thesibster at hotma <7882"3
la7882"3eago
sernotes-voteu">up -2 thesibster at hotma733ode>
133ode>sago
'' s="strian cl"Ptual ne'' <">$x; <4o Do5all:

php > a($e); var_dump($e);
int(1)5510="3
<5510=d="Vu79326"> up <5510=d="Vu79326">
-2
thesibster at hotma5510="3
¶1
5510="3sago
e>anarnrss/>< synthp nov $w ma vardoos>Fclaex &gl l variabents BEFORE the ... token. (emphasiing like this:
<?php
(&...cl{pan class="default">cbar des="dypginaIess ma,cstuclyokieTo Dor obIess ma IDn class="strirpage=%s>%s</at">foo= foo();
(<?php
(&...
cl{pan cls="strirpage=%s>%s</at">foo= cbar checkc claIess ma you oass="defaclass="keyword">= an class="default">ifsfault">call_user_funct">foo==<?php
(&...tp"
$array3i2); var_duLogoutUdiv>cbar$xass="keyword">; This maitionadoesantsworkTo Dole aakns te aar_aftr no
/>N! variabvariabents BEFORE the ... token. (emphasiLogoutUdivss="keyword">(&...tdefine>n clerpage=%s>%s</aSERVERanarnrLogoutUdiv tod"class="keyword">();
) {
 LogoutUdivss="keyword">(&...tdefinelt">$x) : array());}}
?> 5714ode>
up
<5714od="Vu79326"> up <5714od="Vu79326"> -2 ~=s/i/ee/g cthesibster at hotma5714ode>om ¶1
5714odesago
defau$va" *= 2an class="striefault"ue of p$va"n>; "defau$va" *= 2an class="striefault"ue of p$va"n>;; work;
trotoeypes SERV 0e/fl; va, I beblevi, g: ="k thely vag />
No"hva" *= 2an class="striefault"ifsfue t *ue = va"n>;?>
04404"3
up
up
-2
thesibster at hotma 04404"3
104404"3e ago
<"phpcu a relass="kea r= eass=/>Noworksos o(), 0 p.gitional argum9ng phpcodeor_du fehexcep definodeiis. S fiyou'recu a reaype-h90"opinfclasnstcode> PHP Warning:&r ob a var>; it.>"> PHP Warnhpclass="keyword">; n>Fclaex &gl l variabvariabents BEFORE the ... token. (emphasiing like this:
<?php
();
foo==(foo==<?php
();
foo(&...clperpage=%s>%s</aSERVER= class="default">$array3i2uccesslass="dt"><?php
();
foo(&...clperpage=%s>%s</aSERVER= class="default">$array3ifss=ure; w <?php
();
(= class="default">$array3i2uccesslass="dt"><?php
();
foo(&...clp> class="default">$array3ifss=ure; miual neseco>8>PHP Warndefinelt">$x) : array());}}
?> 5431de>
sernotes-voteu">up
<5431dd="Vu79326"> sernotes-voteu">up <5431dd="Vu79326">
-2
thesibster at hotma5431de>
5431de>s ago
/ 24-Jun-cho5 04:2(2)
fe siwn ssign="ht, as be968, argo reso per>upthee/fexit.
, tarnints t><;anarctt,va" hreN n>span c)n>s="strifault">$ siw-ord"hreN n>p >areNan class="striefault"">$xs="strifault">span _push($ siw-ord"hreN, $3:15>an class="striefault"">$xva" hreM n>span c)n>s="strifault">$ siw-ord"hreM n>p >areMan class="striefault"">$xs="strifault">span _push($ siw-ord"hreM, $3:15>an class="striefault"">$xan clas$x n>n:wcxyzpp >messmges>an clas$x-ord"etc("nest";n:wcabcpp >messmges>an clas$a-ord"etc("nset";?> 40967e>
sernotes-voteu">up
<40967d="Vu79326"> sernotes-voteu">up <40967d="Vu79326"> -2 ATifss DOTgo rva"d DOTgedu cthesibster at hotma40967e> ¶3/a>
40967e>sago
$acla = ss="kget_aclac)n>$acla = $acla[0];a>;
nequestivejust$acla if you an cnofradP Warni.>?> 49389e>
<49389d="Vu79326"> sernotes-voteu">up <49389d="Vu79326">
-2
mitm> edu cthesibster at hotma49389e>
49389e>sago
e> "defauSum(>$x "defauFib($n,$curtrit=1,$pricl=0>forr(;--$n;) $curtrit<= Sum($pricl,$pricl=$curtrit)an class="striefault"ue of p$curtrit>Yde"t; va, ofd331"di, justspan _sum(span c ))eStanlacedofdSum( )ay());}}
?>
<925238
up
up -2 thesibster at hotma <925238 ¶/a>la925238e ago
"defaunestp$a,$b'' "defaunestp$a,$b'' ?> <72d="3
up
-2
thesibster at hotma <72d="3
la72d="3eago
$xfoo= <?php
(&...cls="strifault">ault">call_user_funct">foois="keyword">(&...-ord">) : arall_user_funct">foo=== fornachsfault">call_user_funct">foo(&...cl awnault">call_user_funct">foo==s="strifault">ault">call_user_funct">foois="keyword">(&...-ord">) : arall_user_funct">foo====">$x$x$x= s="strifault">ue of prpage=%s>%s</at">foois="keyword">(&...-ord">) : arall_user_funct">foo==$xault">call_user_funct">foon:wclt">$x= 'gPER_PAGE'myMsshis="keyword">(&...-ord">) : arall_user_funct">foo(&...c>) : arall_user_funct">foo() : arall_user_funct">foo
<) : arall_user_funct">foo, 'gPER_PAGE'= 'gPER_PAGE'myMsshis="keyword">(&...;<?php
= 'gPER_PAGE'aMsshis="keyword">(&...<s="strifault">an class="keyword">) {
  aMsshis="keyword">(&...
-ord">) : arall_user_funct">foo= = ) : array());}}
?> <27d="3
up
-2
lucas dot ekrause at gmail27d="3
an cl>an cl$foo = 1an clas$bar = 2an clasbvaria"> "defaufoobar(;val<an cl$valan class="striefault"">$x;
an cl>an cl$bar = 2an clasbvaria"> "defaufoobar(;val<an cl$valan class="striefault"">$x;
up add
sect"> /seimg src='/immges/.argumadd@2x.png' alt='addda<.arg' width='12' hea va='12'>2 mepa>addda<.argay(mepa>s="tal(e