Hudzilla.org - the homepage of Paul Hudson
Contents > Functions Wish List | Report Bug | About Me ]

4.15     User functions

This is NOT the latest copy of this book; click here for the latest version.

Despite the fact that PHP comes with such a large array of functions to perform all sorts of tasks, you are likely to want to create your own functions when the need arises. Whether it is because you find yourself doing the same thing very often, or perhaps it is because you want to share code across projects - user functions are for you.

You can give your functions whatever name you like - they follow the same guidelines (without the $) as PHP's variable. Note, though, that you may not redefine PHP's built-in functions.

The simplest user function in PHP looks something like this:

<?php
    
function foo() {
        return
1;
    }

    print
foo();
?>

As you can see, you define your functions with the function keyword, followed by the name of the function and two brackets. The actual code your function will execute lies between braces - in our example function $foo our sole line of code is "return 1"; we will get onto that in a moment.

After the function definition, we can treat foo() like any other function, as seen in line four where we print out the value it returns. And what value does it return? Well, unsurprisingly, a function returns its return value .





<< 4.14 Altering the execution environment: ini_get(), ini_set(), and set_time_limit()   4.15.1 Return values >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Unix Programmer - 07 Jan 2009

In, "The actual code your function will execute lies between braces - in our example function $foo our sole line of code is "return 1"; we will get onto that in a moment.", the '$' on the front of '$foo' should be removed.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is eight plus seven?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow