Functions are arguably one of the most useful features of PHP. They allow a programmer to encapsulate sections of code within a structure which can then be executed from anywhere else in the program flow. Functions are instantiated by use of the function keyword, followed by the user-defined function name including a list of parameters between the paretheses (but we’ll worry about that in a moment) and the body of the function is contained between braces.
Just as when defining variables, specific naming conventions must be adhered to. A function name can contain letters, numbers and underscores, and must not start with a number. They are also, like variables, case-sensitive. A (very simple) example:
function my_function(){ echo "Hello world"; $a = 5; echo "The value of \$a is $a"; } my_function();
Hello world The value of $a is 5
- Line 1 : The definition of the function. This declares that you, the programmer, have decided to create a function for use called “my_function”. The empty brackets () will be filled in later, but they are important and you cannot leave them out.
- Lines 2-4 : Inside the braces you can place whatever code you desire
- Line 6 : This is a function call and lets PHP know that we want to execute the function at this point. This differs from the function declaration in that we are not using the function keyword to create a function. This function call can occur anywhere within the code, as long as it occurs after the function has been declared




September 30th, 2008 at 10:34 am
The section containing the following:
//begin paste from web page
$a = 100;
function my_function($a){
global $a;
$b = 10;
echo $b+$a;
}
my_function(21);
will produce
121
//end paste from web page
Will actually produce 110. I know you know what you are doing, but just wanted to point out this typo to you. I am really glad you have published this PHP tutorial, I started going through it this morning and it is great. Thanks so much for putting all this together.
Zach
September 30th, 2008 at 10:55 am
Ah yes, thanks for pointing that out
I’m glad you’re finding the tutorials useful!
October 27th, 2008 at 3:56 pm
Great tutorial. Thanks