PHP Advanced Concepts

Anatomy of a Class

In it's most basic form, a Class consists of Class Variables, a Class Constructor and Class Methods (which are simply Class Functions by another name).

As you might expect, Class Variables, once set in the Class, will be available to all objects formed by the Class, much like global variables in basic PHP programming. Within the Class, they are accessed with the keyword 'this' and a '->' connector. Within the object, they are accessed by the object name and the same connector. Revisit the Database Class on the previous page for an example.

You create variables within a Class with the var keyword. This tells the class that this variable is global.

In OOP, an object is said to be an instance of the Class. If a Class Constructor is defined within the Class, it is automatically called when the object is created. The Class Constructor must be a Method within the Class with the same name as the Class itself. Typically, the Class Constructor sets the default values for the Class Variables and whatever other initial chores must be done for the object.

The Class Methods are the default functions you want available for all objects formed by the Class. Among other things, the Class Methods typically 'get' and 'set' the global Class Variables (these are called accessor methods).

And that's it for OOP. To recap, you create a file for the Class, which consists of Class Variables, a Class Constructor and Class Methods. In any file you wish to create an instance of that class, (an object), you first include the file containing the Class, then create the object by setting some variable equal to a new instance of the Class. Now the object has all the variables and methods of the class available.

<?php include_once("database.inc"); . . . $DB = new Database(); $DB->OpenConnection($DB->GetHost(), $DB->GetUsername(), $DB->GetPassword(), $DB->GetDBName()); $Query = "INSERT INTO Table (Field1, Field2) VALUES ('Value1', 'Value2')"; $DB->ExecuteQuery($Query); $DB->CloseConnection(); . . . ?>

Here is a site that helps you create Class files.


Object Oriented Programming   < <  PREVIOUS   Table of Contents NEXT  > >   Quote Tricks

Developed with HTML-Kit
Sandersongs Web Tutorials
Contact the Webmasterwith comments.
©2017, by Bill Sanders, all rights reserved.
This domain had 3,933 different visits in the last 30 days.
435,408 hits on this domain since 24 Nov 2006.
http://sandersongs.com/PHPsqlCourse/PHPadv11.php
This page was last modified on our server on 4 Jun 2008
and last refreshed on our server at 12:17 pm, MST
This file took 0.00826 seconds to process.