Chapter 5. Groups of Logic: Functions and Files
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 engine).
The basics of defining your own functions and using them are laid out in the next section, “Declaring and Calling Functions”. When you call a function, you can hand it some values with which to operate. For example, if you wrote 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. “Passing Arguments to Functions” explains how to write functions that accept arguments and how to use the arguments from inside the functions.
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 ...
Get Learning PHP 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.