PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<include_onceFunktionsparameter>
view the version of this page
Last updated: Sat, 19 Apr 2003

Kapitel 13. Funktionen

Vom Nutzer definierte Funktionen

Eine Funktion kann wie folgt definiert werden:

function foo ($arg_1, $arg_2, ..., $arg_n)
{
    echo "Beispielfunktion.\n";
    return $retval;
}

Jeder beliebige korrekte PHP-Code kann in einer Funktion vorkommen, sogar andere Funktionen und Klassen- Definitionen.

In PHP 3 m�ssen Funktionen definiert sein, bevor man auf sie verweist. In PHP4 ist das nicht mehr erforderlich, au�er wenn eine Funktion nur bedingt definiert wird, wie in den beiden untenstehenden Beispielen gezeigt.

Wenn eine Funktion nur unter bestimmten Bedingungen definiert wird, mu� die Definition dieser Funktion noch vor deren Aufruf abgearbeitet werden.

Beispiel 13-1. Bedingte Funktionen

<?php

$makefoo = true;

/* Wir k�nnen foo() von her aus nicht
   aufrufen, da sie noch nicht existiert,
   aber wir k�nnen bar() aufrufen */

bar();

if ($makefoo) {
  function foo ()
  {
    echo "Ich existiere nicht, bis mich die Programmausf�hrung erreicht hat.\n";
  }
}

/* Nun k�nnen wir foo() sicher aufrufen,
   da $makefoo als true ausgewertet wurde */

if ($makefoo) foo();

function bar()
{
  echo "Ich existiere sofort nach Programmstart.\n";
}

?>

Beispiel 13-2. Funktionen innerhalb von Funktionen

<?php
function foo() 
{
  function bar() 
  {
    echo "Ich existiere nicht, bis foo() aufgerufen wurde.\n";
  }
}

/* Wir k�nnen bar() noch nicht
   aufrufen, da es nicht existiert */

foo();

/* Nun k�nnen wir auch bar() aufrufen,
   da sie durch die Abarbeitung von
   foo() verf�gbar gemacht wurde */

bar();

?>

PHP unterst�tzt weder das �berladen von Funktionen, noch ist es m�glich, zuvor deklarierte Funktionen neu zu definieren oder die Definition zu l�schen.

PHP 3 unterst�tzt keine variable Anzahl von Parametern, obwohl Vorgabewerte f�r Parameter unterst�tzt werden (weitere Informationen finden Sie unter Vorgabewerte f�r Parameter). PHP 4 unterst�tzt beides: siehe Variable Parameteranzahl und die Funktionsreferenzen f�r func_num_args(), func_get_arg() und func_get_args() f�r weitere Informationen.



User Contributed Notes
Funktionen
add a note
brooke at wayport dot net
08-Nov-1999 07:21

Many people ask how to call functions that are in other files. See "Require"  and "Include" in the manual. Also the value of $DOCUMENT_ROOT is good for including sub-includes. (It is NOT like C/C++ includes. The dir is ALWAYS relative to the main source file.)
php at paintbot dot com
05-Feb-2000 02:32

Important Note to All New Users: functions do NOT have default access to GLOBAL variables.  You must specify globals as such in your function using the 'global' type/keyword.  See the section on variables:scope.

This note should also be added to the documentation, as it would help the majority of programmers who use languages where globals are, well, global (that is, available from anywhere).  The scoping rules should also not be buried in subsection 4 of the variables section.  It should be front and center because I think this is probably one of the most non-standard and thus confusing design choices of PHP.

[Ed. note: the variables $_GET, $_POST, $_REQUEST, $_SESSION, and $_FILES are superglobals, which means you don't need the global keyword to use them inside a function]

cap at capsi dot cx
22-Feb-2000 11:19

When using a function within a function, using global in the inner function will not make variables available that have been first initialized within the outer function.
GMCardoe at netherworldrpg dot net
24-Apr-2000 09:02

Stack overflow means your function called itself recursivly too many times and just completely filled up the processes stack. That error is there to stop a recursive call from completely taking up the entire system memory.
php-general at list dot php dot net
05-Dec-2000 11:51

If a user-defined function does not explicitly return a value, then it
will return NULL. For most truth tests, this can be considered as FALSE.

For example:

function print_list ($array)
{
print implode ("<br />", $array);
}

if (print_list ($HTTP_POST_VARS))
print "The print_list function returned a value that can be considered true."
else
print "The print_list function returned a value that can be considered false."

kop at meme dot com
14-Dec-2000 10:14

See also about controlling the generation of error messages by putting @ in front of the function before you call it, in the section "error control operators".
21-Dec-2000 05:41
Function names are case-insensitive in PHP 3 and PHP 4.

For example, if you have function foo, you can call it using foo(), FoO(), FOO(), etc..

yasuo_ohgaki at hotmail dot com
09-Mar-2001 05:42

PHP supports recursion. I thought it worth to mention.

Simple Quick Sort using recursion works perfectly.

== OUTPUT ==
Recursion TEST

Array
(
   [0] => 12
  [1] => 23
   [2] => 35
   [3] => 45
   [4] => 56
   [5] => 67
)
== END OUTPUT ==

== QUICK SORT CODE ==
<?php

echo('
Recursion TEST
');

function swap(&$v, $i, $j) {
$temp = $v[$i];
$v[$i] = $v[$j];
$v[$j] = $temp;
}

// Quick Sort integer array - $int_array[$left] .. $int_array[$right]
function qsort(&$int_array, $left, $right) {
if ($left >= $right)
return; // Do nothing if there are less than 2 array elements
swap ($int_array, $left, intval(($left+$right)/2));
$last = $left;
for ($i = $left + 1; $i <= $right; $i++)
 if ($int_array[$i] < $int_array[$left])
  swap($int_array, ++$last, $i);
swap($int_array, $left, $last);
qsort($int_array, $left, $last-1);
qsort($int_array, $last+1, $right);
}

$val = array(56,23,45,67,12,35);

qsort($val, 0, count($val)-1);

echo '<pre>';
print_r ($val);
echo '</pre>';

?>
== END QUICK SORT ==

aboyd at ssti dot com
05-Apr-2001 03:34

[Editor's note: put your includes in the beginning of your script. You can call an included function, after it has been included               --jeroen]

The documentation states: "In PHP 3, functions must be defined before they are referenced. No such requirement exists in PHP 4."

I thought it wise to note here that there is in fact a limitation: you cannot bury your function in an include() or require(). If the function is in an include()'d file, there is NO way to call that function beforehand.  The workaround is to put the function directly in the file that calls the function.

xpaz at somm dot com
14-Nov-2001 07:47

It is possible to define a function from inside another function.
The result is that the inner function does not exist until the outer function gets executed.

For example, the following code:

function a () {
 function b() {
   echo "I am b.\n";
 }
 echo "I am a.\n";
}
if (function_exists("b")) echo "b is defined.\n"; else echo "b is not defined.\n";
a();
if (function_exists("b")) echo "b is defined.\n"; else echo "b is not defined.\n";

echoes:

b is not defined.
I am a.
b is defined.

Classes too can be defined inside functions, and will not exist until the outer function gets executed.

fabio at city dot ac dot uk
14-Feb-2002 01:57

As a corollary to other people's contributions in this section, you have to be careful when transforming a piece of code in to a function (say F1). If this piece of code contains calls to another function (say F2), then each variable used in F2 and defined in F1 must be declared as GLOBAL both in F1 and F2. This is tricky.
bishop
01-May-2002 02:49

The documentation statement:

"In PHP 3, functions must be defined before they are referenced. No such requirement exists in PHP 4."

is not entirely accurate (or at least misleading).

Consider:
function a() {
   function b() {
     echo 'I am b';
   }
   echo 'I am a';
}

You MUST call a() before you can even think about using b().  Why? The parser hasn't touched the scope inside function a (for efficiency reasons), so b has yet to be defined or even *declared*.

The documentation (I believe) refers to this behaviour:
a();

function a() {
 echo 'I am a';
}

which is perfectly valid and runs as you probably expect.  However, the following does not work as expected (or documented):

function a() {
   b();

   function b() {
       echo 'I am b';
   }
   echo 'I am a';
}

a();

Rather than getting "I am b" followed by "I am a" you get a parse error ("Call to undefined function b()").

So, the bottom line: Gewaehrleistungsausschluss

bishop
01-May-2002 02:54

Consider:

function a() {
   function b() {
       echo 'I am b';
   }
   echo 'I am a';
}

a();
a();

As you might NOT expect, the second call to a() fails with a "Cannot redeclare b()" error.  This behaviour is correct, insofar as PHP doesn't "allow functions to be redefined."

A work around:
function a() {
   if ( ! function_exists('b') ) {
      function b() {
           echo 'I am b';
       }
   }
  echo 'I am a';
}

devciti at yahoo dot com
20-Jun-2002 04:51

I have some problems with functions. I want to create some kind of 'tell me the configuration function'. Like this:
<?php
function TellConfig(){
$header_file_to_use = "header.inc";
$footer_file_to_user = "footer.inc";
}
//Wont Work!
TellConfig();
include($header_file_to_use);
echo "Body!";
include($footer_file_to_use);
/*
Is there a way to call a variable set by a function? As i dont know this is the way i am doing it
*/
$header_file_to_use = "";
$footer_file_to_use  = "";
function TellConfig2(){
global $header_file_to_use, $footer_file_to_use;
$header_file_to_use = "header.inc";
$footer_file_to_use  = "footer.inc";
}
TellConfig2();
include($header_file_to_use);
echo "body 2!";
include($footer_file_to_use);
// This works
?>

Even i dont want to use a function for configuration vars this is a good example.
:P

germanAlonso at keltoi-web dot com
10-Aug-2002 02:17

Although [email protected] has already pointed the recursion support on PHP, here's another example, wich shows clearly the mechanism of recursive algorithms:

function fact($i){
 if($i==1){
  return 1;
 }else{
   return $i*fact($i-1);
 }
}

It returns $i! (supposing $i is a valid positive integer greater than 0).

matt at smidwap dot com
14-Aug-2002 12:26

[Editor's note: that is the reason why 'function' and others are "reserved words", see: for more details]

Creating a function with the name 'function' won't turn up errors, but when calling that function, nothing will be returned.  Example:

<?php
function();
function function () {
print "Hello, world!";
}
// "Hello, world!" will not be printed.
?>

I assume this is because when calling 'function', php thinks you are trying to create a new function.

06-Sep-2002 08:41
If you need to use "real" global variables, accessible from any function, without the need to declare them explicity, take a look at (join these 2 lines please):

s=1ac53d13a815427f145d5dedf6a10023&threadid=10209242

albaity at php4web dot com
26-Oct-2002 02:06

To use class from function
you need first to load class OUT the function
and then you can use the class functions from your function
example :
class Cart
{
   var $items;  // Items in our shopping cart
 
   // Add $num articles of $artnr to the cart

   function add_item ($artnr, $num)
   {
      $this->items[$artnr] += $num;
   }
 
   // Take $num articles of $artnr out of the cart

   function remove_item ($artnr, $num)
   {
       if ($this->items[$artnr] > $num) {
           $this->items[$artnr] -= $num;
           return true;
       } else {
           return false;
       }  
  }
}

------------------------
<?php
$cart = new Cart;

function additem($var1,$var2){
$cart->add_item($var1, $var2);
}
additem(1,10);
?>

allen at brooker dot gb dot net
21-Nov-2002 03:23

Does anyone have a list of all the characters allowed in function names?

So far I've only used a-z 0-9 _ and -
I assume (), {}, [], ', ", $, % and & are not allowed.

What other characters are legal and what aren't?

bitparanoid at yahoo dot com
15-Dec-2002 05:38

Example 13.1 has an extra curly brace which will throw back an error:

function bar() {
{
  echo "I exist immediately....
}

should be:

function bar() {
 echo "I exist immediately...
}

misc dot anders at feder dot dk
24-Dec-2002 10:28

PHP allows you to address functions in a very dynamic way:

$foo = "bar";
$foo("fubar");

The above will call the bar function with the "fubar" argument.

mittag /// add /// marcmittag /// de
23-Jan-2003 11:31

To devciti at yahoo dot com

The section "returning values" of the docu says:

=====
You can't return multiple values from a function, but similar results can be obtained by returning a list.

function small_numbers()
{
   return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
=====

nutbar at innocent dot com
12-Mar-2003 07:06

Regarding the comments about having to declare global variables inside of functions before you can use them...

Lots of you seem to complain about having to declare lots of variables, when really there's one simple solution to this:

global $GLOBALS;

This will define the $GLOBALS variable inside your code, and since that variable is basically like the mother of all variables - *presto*, you now have access to any variable in PHP.

gayard at ig dot com dot br
04-Apr-2003 10:58

In PHP 4.3.0, I have found a bug in declaring functions within functions:

<?

function MyZero($x) {
 function GreaterThanZero() { echo "Greater"; }
 function LessThanZero()    { echo "LessThan"; }
 function EqualToZero()     { echo "Equal"; }
 
 if ($x > 0) GreaterThanZero();
 else if ($x < 0) LessThanZero();
 else EqualToZero();
}

 MyZero(1);
 MyZero(0);
MyZero(-1);

?>

The output is:
Greater
Fatal error: Cannot redeclare greaterthanzero() (previously declared in /home/php/public_html/teste.php:4) in /home/php/public_html/teste.php on line 4

My advice is: declare functions like you did in C, that is one function at a time. This seems to work fine.

php at simoneast dot net
11-Apr-2003 04:59

If you're frustrated by not having access to global variables from within your functions, instead of declaring each one (particularly if you don't know them all) there are a couple of workarounds...

If your function just needs to read global variables...

function aCoolFunction () {
extract($GLOBALS);
....

This creates a copy of all the global variables in the function scope.  Notice that because it's a copy of the variables, changing them won't affect the variables outside the function and the copies are lost at the conclusion of the function.

If you need to write to your global variables, I haven't tested it, but you could probably loop through the $GLOBALS array and make a "global" declaration for each one.  Then you could modify the variables.

Please note that this shouldn't be standard practice, but only in the case where a function needs access to all the global variables when they may be different from one call to another.  Use the "global var1, var2..." declaration where possible.

Hope that helps some people.

Simon.

Storm
10-May-2003 02:55

I think it worthy of noting (for noobies such as myself):
You can define access to a global variable before it is defined when defining a function as long as the variable is defined before the function is called. This had me baffled for a few hours til I tried it out...lol. Here's a quick example:

Perfectly valid:
-------------------------
function hello() {
  global $hi;

  echo $hi;
}

$hi = 'Hi There!'; // Var defined after function is defined

hello();
-------------------------

I know most of the Gurus persay already knew this, but I didn't! :p This helps ;-)

add a note

<include_onceFunktionsparameter>
 Last updated: Sat, 19 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Mon May 12 21:12:21 2003 CEST