PHP Functions

From Techotopia
Revision as of 19:57, 31 May 2007 by Neil (Talk | contribs) (How to Write a PHP Function)

Jump to: navigation, search

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";
}
?>