Access and Adapt a Database with MySQL Queries
MySQL Account Names and Hostnames
How to Build a Contact Page on a PHP Template

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:

$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.

/* Script name: buildForm
 * Description: Uses the form to create a simple HTML form
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");
echo "<h3>Please fill out the following form:</h3>";
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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
PHP Template Systems
How to Use PHP Variables for HTML5 and CSS3 Programming
PHP Data Types
How to Restore Your MySQL Data
Combine Information from Multiple MySQL Tables with UNION