Chapter 5. PHP Functions and Objects

The basic requirements of any programming language include somewhere to store data, a means of directing program flow with statements like if and else, and a few bits and pieces such as expression evaluation, file management, and text output. PHP has all these 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 to call the code.

In PHP 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

  • Accept arguments and can therefore be used for general as well as specific cases

  • Are easier to write tests for

Object-oriented programming takes this concept a step further. A class is like a template that allows you to create objects, which encapsulate one ore more functions and the data they use.

In this chapter, you’ll learn all about using functions, from defining and calling them to passing arguments. With that knowledge under your belt, you’ll start creating functions and using ...

Get Learning PHP, MySQL & JavaScript, 7th Edition 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.