Chapter 5. Functions
When you’re writing computer programs, laziness is a virtue. Reusing code you’ve already written makes it easier to do as little work as possible. Functions are the key to code reuse. A function is a named set of statements that you can execute just by invoking the function name instead of retyping the statements. This saves time and prevents errors. Plus, functions make it easier to use code that other people have written (as you’ve discovered by using the built-in functions written by the authors of the PHP interpreter).
The basics of defining your own functions and using them are laid out in Section 5.1. When you call a function, you can hand it some values with which to operate. For example, if you write a function to check whether a user is allowed to access the current web page, you would need to provide the username and the current web page name to the function. These values are called arguments. Section 5.2 explains how to write functions that accept arguments and how to use the arguments from inside the function.
Some functions are one-way streets. You may pass them arguments, but you don’t get
anything back. A print_header( )
function that prints the top of an HTML page may take an argument containing the page title, but it doesn’t give you any information after it executes. It just displays output. Most functions move information in two directions. The access control function mentioned above is an example of this. The function gives you back a value: ...
Get Learning PHP 5 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.