Lesson 14

Using Classes

In the previous lesson you learned how to define classes. In this lesson you learn how to use them.

Instantiating the Class

A class is a blueprint for creating objects. When you create an object you are instantiating the class—making an instance of the class. You can create multiple objects from the same class. They all start out the same, with properties empty or equal to a default and with the capability of performing all the actions detailed by the methods. They are all independent so when you change a property in one, it does not affect the property in any of the other objects made from that class. It is just like when you enter a contact in your cell phone; no one else's cell phone is affected.

Instantiating the class is very easy. Make sure that the class code has been included. Use a require_once to include it. You need the file, so it should be a require rather than an include. You also want the class to be included only once because you get an error if you try to define the class a second time, even if it is identical. It is standard practice to include your common classes when you start the program. If you rarely use a class, you can include it before you create an object.

If a class called Cellphone is in the cellphone.php file, the following code creates an object called $myPhone:

require_once ‘cellphone.php’;
$myPhone = new Cellphone();

The object called $myPhone is a regular variable that happens to be an object. You use all the ...

Get PHP and MySQL® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.