Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Functions

Despite the fact that PHP comes with such a large selection of functions to perform all sorts of tasks, you will want to create your own functions when the need arises. If you find yourself doing the same thing repeatedly, or you want to share code across projects, user functions are for you.

Writing monolithic programs—code that starts at the beginning and runs straight through to the end—is considered very bad for program maintainability, as you are not able to reuse code. By writing functions, you make your code shorter, easier to control and maintain, and less prone to bugs.

A Simple User Function

You can give your functions whatever name you like; they follow the same guidelines (without the $) as PHP's variables. You may not redefine PHP's built-in functions, and care should be taken to ensure that your function names do not collide with existing PHP functions—just because you don't have the imagepng() function available, it doesn't mean others also won't.

The simplest user function in PHP looks something like this:

    function foo() {
            return 
 1;
    }

    print foo();

You define your functions with the function keyword, followed by the name of the function and two parentheses. 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 to 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 (known as ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page