Chapter 6. Functions


Functions help you create organized and reusable code. They allow you to abstract out details so your code becomes more flexible and more readable. Without functions, it is impossible to write easily maintainable programs because you’re constantly updating identical blocks of code in multiple places and in multiple files.

With a function you pass a number of arguments in and get a value back:

function add($a, $b) {
    return $a + $b;

$total = add(2, 2);
// $total is 4

Declare a function using the function keyword, followed by the name of the function and any parameters in parentheses. To invoke a function, simply use the function name, specifying argument values for any parameters to the function. If the function returns a value, you can assign the result of the function to a variable, as shown in the preceding example.

You don’t need to predeclare a function before you call it. PHP parses the entire file before it begins executing, so you can intermix function declarations and invocations. You can’t, however, redefine a function in PHP. If PHP encounters a function with a name identical to one it’s already found, it throws a fatal error and dies.

Sometimes, the standard procedure of passing in a fixed number of arguments and getting one value back doesn’t quite fit a particular situation in your code. Maybe you don’t know ahead of time exactly how many parameters your function needs to accept. Or you do know your parameters, but they’re almost always ...

Get PHP Cookbook, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.