Object-Oriented PHP: Constructors and Destructors - Autoloading Objects
(Page 6 of 6 )
For organizational reasons, it’s common practice to place each class in a separate file. Returning to the library scenario, suppose the management application called for classes representing books, employees, events, and patrons. Tasked with this project, you might create a directory named classes and place the following files in it: Books.class.php, Employees.class.php,Events.class.php, andPatrons.class.php. While this does indeed facilitate class management, it also requires that each separate file be made available to any script requiring it, typically through therequire_once()statement. Therefore, a script requiring all four classes would require that the following statements be inserted at the beginning:
Managing class inclusion in this manner can become rather tedious, and adds an extra step to the already often complicated development process. To eliminate this additional task, the concept of autoloading objects was introduced in PHP 5. Autoloading allows you to define a special__autoloadfunction that is automatically called whenever a class is referenced that hasn’t yet been defined in the script. Returning to the library example, you can eliminate the need to manually include each class file by defining the following function:
function __autoload($class) { require_once("classes/$class.class.php"); }
Defining this function eliminates the need for therequire_once()statements, because when a class is invoked for the first time,__autoload()will be called, loading the class according to the commands defined in__autoload(). This function can be placed in some global application configuration file, meaning only that function will need to be made available to the script.
■Note Therequire_once()function and its siblings are introduced in Chapter 10.
Summary
This chapter introduced object-oriented programming fundamentals, followed by an overview of PHP’s basic object-oriented features, devoting special attention to those enhancements and additions that are new to PHP 5.
The next chapter expands upon this introductory information, covering topics such as inheritance, interfaces, abstract classes, and more.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.