PHP Functions

Revision as of 20:04, 31 May 2007 by Neil (Talk | contribs) (Returning a Value from a PHP Function)

Revision as of 20:04, 31 May 2007 by Neil (Talk | contribs) (Returning a Value from a PHP Function)

In the world of programming and scripting there are two ways to write code. One way is to write long, sprawling and monolithic sections of script. Another is to break the scripts up into tidy, self contained modules that can be re-used without having to re-invent the same code over and over again. Obviously the latter is highly preferable to the former, and the fundamental building block of this appraoch to writing PHP scripts in the function.

What is a PHP Function?

Functions are basically named scripts that can be called upon from any other script to perform a specifc task. Values (known as arguments) can be passed into a function so that they can be used in the function script, and functions can, in turn, return results to the location from which they were called.

PHP functions exist it two forms, functions that are provided with PHP to make your life as a web develeper easier, and those that you as a web developer create yourself.

How to Write a PHP Function

the first step in creating a PHP function is provide a name by which you will reference the function. Naming conventions for PHp functions are the same as those for variables in that they must begin with a letter or an underscore and must be devoid of any kind of white space or punctuation. You must also take care to ensure that your function name does not conflict with any of the PHP built in functions.

PHP functions are created using the function keyword followed by the name and, finally a set of parentheses. The body of the function (the script that performs the work of the function) is then enclosed in opening and closing braces.

The following example function simply output a string when it is called:

<?php
function sayHello()
{
       print "Hello";
}
?>

Returning a Value from a PHP Function

A single value may be returned from a PHP function top the script from which it was called. The returned value can be any variable type of your choice.

The return keyword is used to return the value:

<?php
function returnTen ()
{
     return 10;
}
?>

The above example returns the value of 10 to the calling script.

Passing Parameters to a PHP Function

Parameters (or arguments as they are more frequently known) can be passed into a function. There are no significant restrictions of the number of arguments which can be passed through to the function.

A function can be designed to accept parameters by placing the parameter names inside the parentheses of the the function definition. Those variables can then be accessed from within the function body as follows:

<?php
function addNumbers ($val1, $val2)
{
     return $val1 + $val2;
}
?>

In the above example the addNumbers() function accepts two parameters as arguments, add them, together and returns the result.