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 else and elseif to make life easier. But even with all
these in your toolkit, programming can be clumsy and tedious, especially if
you have to rewrite portions of very similar code each time you need
them.
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:
Less typing is involved.
Functions reduce syntax and other programming errors.
They decrease the loading time of program files.
They also decrease execution time, because each function is compiled only once, no matter how often you call it.
Functions 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 ...
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.
Read now
Unlock full access