PHP  
downloads | documentation | faq | getting help | | php.net sites | links 
search for in the  
previousinclude_onceArgomenti delle funzioninext
Last updated: Wed, 10 Jul 2002
view this page in Printer friendly version | English | Brazilian Portuguese | Czech | Dutch | Finnish | German | Hungarian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Turkish

Capitolo 12. Funzioni

Funzioni definite dall'utente

Una funzione pu� essere definita usando la seguente sintassi:

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

All'interno di una funzione pu� apparire qualunque codice PHP valido, persino altre funzioni e definizioni di classe.

In PHP 3, le funzioni devono essere definite prima di essere referenziate. Non esiste nessun requisito in PHP 4.

PHP non supporta l'overloading di funzioni, non � possibile indefinire o ridefinire funzioni precedentemente dichiarate.

PHP 3 non supporta un numero variabile di argomenti per le funzioni, sebbene siano supportati gli argomenti di default (vedere Argomenti con valori di default per maggiori informazioni). PHP 4 li supporta entrambi: vedere Liste di argomenti a lunghezza variabile e i riferimenti alle funzioni func_num_args(), func_get_arg() e func_get_args() per maggiori informazioni.

User Contributed Notes
Funzioni
add a note about notes

08-Nov-1999 06: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.)


05-Feb-2000 01: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]


22-Feb-2000 10: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.


24-Apr-2000 08: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.


05-Dec-2000 10: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."


14-Dec-2000 09: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 04: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..


09-Mar-2001 04: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 ==


05-Apr-2001 02: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.


14-Nov-2001 06: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.


14-Feb-2002 12: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 01: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 01: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';
}


20-Jun-2002 03: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

add a note about notes
previousinclude_onceArgomenti delle funzioninext
Last updated: Wed, 10 Jul 2002
show source | credits | stats | mirror sites:  
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Fri Jul 12 08:19:06 2002 CEST