Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Use a PHP Class in a Script

The PHP 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 here shows how to use the Form class.

<?php
/* Script name: buildForm
 * Description: Uses the form to create a simple HTML form
 */
require_once("Form.class");
echo "<html><head><title>Phone form</title></head><body>";
$phone_form = new Form("process.php","Submit Phone");
$phone_form->addField("first_name","First Name");
$phone_form->addField("last_name","Last Name");
$phone_form->addField("phone","Phone");
echo "<h3>Please fill out the following form:</h3>";
$phone_form->displayForm();
echo "</body></html>";
?>

First, the script includes the file containing the Form class in the script. The class is stored in the file Form.class. The script creates a new form object called $phone_form. Three fields are added with the addField method. The form is displayed with the displayForm method. Notice that some additional HTML code is output in this script. That HTML could have been added to the displayForm method just as easily.

The script creates a form with three fields, using the Form class.

image0.jpg
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!