Chapter 5. PHP Functions and Objects
The basic requirements of any programming language include somewhere
to store data, a means of directing program flow, and a few bits and pieces
such as expression evaluation, file management, and text output. PHP has all
these, plus tools like
elseif to make life easier. But even with all
these in our toolkit, programming can be clumsy and tedious, especially if
you have to rewrite portions of very similar code each time you need
That’s where functions and objects come in. As you might guess, a function is a set of statements that performs a particular function and—optionally—returns a value. You can pull out a section of code that you have used more than once, place it into a function, and call the function by name when you want the code.
Functions have many advantages over contiguous, inline code. For example, they:
Involve less typing
Reduce syntax and other programming errors
Decrease the loading time of program files
Decrease execution time, because each function is compiled only once, no matter how often you call it
Accept arguments and can therefore be used for general as well as specific cases
Objects take this concept a step further. An object incorporates one or more functions, and the data they use, into a single structure called a class.
In this chapter, you’ll learn all about using functions, from defining and calling them to passing arguments back and forth. With that knowledge under your belt, you’ll start creating functions ...