4.4. Using a Class in a Script

The class code needs to be in the script that uses the class. Most commonly, the class is stored in a separate include file and is included in any script that uses the class.

To use an object, you first create the object from the class. Then that object can perform any methods that the class includes. Creating an object is called instantiating the object. Just as you can use a pattern to create many similar but individual dresses, you can use a class to create many similar but individual objects. To create an object, use statements that have the following format:

$objectname = new classname(value,value,...);

Some valid statements that create objects are:

$Joe = new Person("male");
$car_Joe = new Car("red");
$car_Sam = new Car("green");
$customer1 = new Customer("Smith","Joe",$custID);

The object is stored in the variable name, and the constructor method is executed. You can then use any method in the class with statements of the following format:

$Joe->goToWork();
$car_Joe->park("illegal");
$car_Sam->paintCar("blue");
$name = $customer1->getName();

Different objects created from the same class are independent individuals. Sam's car gets painted blue, but Joe's car is still red. Joe gets a parking ticket, but it doesn't affect Sam.

The script shown in Listing 4-2 shows how to use the Form class that was created in the preceding section and shown in Listing 4-1.

Example 4.2. A Script That Creates a Form
<?php /* Script name: buildForm * Description: ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® 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.