Last 5.3 release ever available: PHP 5.3.29 - 5.3 now EOL

User-defined functions

A function may be defined using syntax such as the following:

Example #1 Pseudo code to demonstrate function uses

<?php
function foo($arg_1$arg_2/* ..., */ $arg_n)
{
    echo 
"Example function.\n";
    return 
$retval;
}
?>

Any valid PHP code may appear inside a function, even other functions and class definitions.

Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Tip

See also the Userland Naming Guide.

Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.

Example #2 Conditional functions

<?php

$makefoo 
true;

/* We can't call foo() from here 
   since it doesn't exist yet,
   but we can call bar() */

bar();

if (
$makefoo) {
  function 
foo()
  {
    echo 
"I don't exist until program execution reaches me.\n";
  }
}

/* Now we can safely call foo()
   since $makefoo evaluated to true */

if ($makefoofoo();

function 
bar() 
{
  echo 
"I exist immediately upon program start.\n";
}

?>

Example #3 Functions within functions

<?php
function foo() 
{
  function 
bar() 
  {
    echo 
"I don't exist until foo() is called.\n";
  }
}

/* We can't call bar() yet
   since it doesn't exist. */

foo();

/* Now we can call bar(),
   foo()'s processing has
   made it accessible. */

bar();

?>

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

Note: Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.

Both variable number of arguments and default arguments are supported in functions. See also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

It is possible to call recursive functions in PHP. However avoid recursive function/method calls with over 100-200 recursion levels as it can smash the stack and cause a termination of the current script.

Example #4 Recursive functions

<?php
function recursion($a)
{
    if (
$a 20) {
        echo 
"$a\n";
        
recursion($a 1);
    }
}
?>

add a note add a note

User Contributed Notes 5 notes

up
7
aydinantmen [at] hotmail [dot] com
3 months ago
I want to use multidimentional arrays in a callback function what accepts second parameter.

Solution:

<?php

$arr1
= array("a" => "b", "c", "d's", "e" => array("f's", "g" => array("h's", "i" => "j's")));
$arr2 = mdarr_parameter($arr1);
$arr3 = mdarr_parameter($arr2, true);

function
mdarr_parameter($needle, $job=false) {
    if (
is_array($needle)) {
        foreach(
$needle as $name => $value) {
           
$needle[$name] = mdarr_parameter($value, $job);
        }
    } else {
       
// Now you do anything you want...
       
if ($job === true) {
           
$needle = stripslashes($needle);
        } else {
           
$needle = addslashes($needle);
        }
    }
    return
$needle;
}

print_r($arr2);
print_r($arr3);

/**
Outputs:

Array
(
    [a] => b
    [0] => c
    [1] => d\'s
    [e] => Array
        (
            [0] => f\'s
            [g] => Array
                (
                    [0] => h\'s
                    [i] => j\'s
                )

        )

)
Array
(
    [a] => b
    [0] => c
    [1] => d's
    [e] => Array
        (
            [0] => f's
            [g] => Array
                (
                    [0] => h's
                    [i] => j's
                )

        )

)
**/

?>
up
5
webmaster at heathdale dot vic dot edu dot au
4 months ago
<?php

// first run (function doesn't exist)
$myfunc_exists;
if (!
$myfunc_exists) {
    function
myfunc() {
        echo (
'myfunc ran definition #1<br>');
    }
   
$myfunc_exists = true;
}

myfunc();   // echoes 'myfunc ran definition #1<br>'

// second run (function already exists, so won't be redefined and won't cause error)
// e.g. if the file containing the function got #included twice (it does happen)
$myfunc_exists;
if (!
$myfunc_exists) {
    function
myfunc() {
        echo (
'myfunc ran definition #2<br>');
    }
   
$myfunc_exists = true;
}

myfunc();  // still echoes 'myfunc ran definition #1<br>' (not #2)

?>
up
-8
Alexandre
2 months ago
In  PHP version less than 5 a function named "retorna_so_numeros" was OK.

Now in current PHP version I had to rename this function to "retorna_numeros" or the script won't work.
up
-36
Ben Tiessen
6 months ago
Functions can also be executed from variables:

function myFunc(){
  echo "Hello World";
}

$myFunc = myFunc();

$myFunc();

// Will output Hello World
up
-37
lubaev
7 months ago
<?php

function overload()
{
 
$overloadFn = array();
 
 
// key = count arguments, value = callback function.
 
$overloadFn[0] = function() {
    return print
nl2br("Zero argument. \n");
  };
 
$overloadFn[1] = function($a) {
    return print
nl2br("One argument. Result: $a \n");
  };
 
$overloadFn[2] = function($a,$b) {
    return print
nl2br("Two argument. Result: $a, $b \n");
  };
 
$overloadFn[4] = function($a,$b,$c,$d) {
    return print
nl2br("Four argument. Result: $a, $b, $c, $d \n");
  };
 
 
$countArgs = func_num_args();
 
$valueArgs = func_get_args();
 
  if( isset(
$overloadFn[ $countArgs ]) )
  {
    return
call_user_func_array( $overloadFn[ $countArgs ], $valueArgs );
  }
 
trigger_error("Wrong number of arguments!", E_USER_WARNING);
 
}

// OVERLOAD
overload(); // Zero argument.
overload(1); // One argument. Result: 1
overload(1,2); // Two argument. Result: 1, 2
overload(1,2,3); // Warning: Wrong number of arguments!
overload(1,2,3,4); // Four argument. Result: 1, 2, 3, 4
overload(1,2,3,4,5); // Warning: Wrong number of arguments!

?>
To Top