11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

www.it-ebooks.infoCHAPTER 6 • OBJECT-ORIENTED <strong>PHP</strong>Autoloading ObjectsFor organizational reasons, it’s common practice to place each class in a separate file. Returning to thelibrary scenario, suppose the management application calls for classes representing books, employees,events, and patrons. Tasked with this project, you might create a directory named classes and place thefollowing files in it: Books.class.php, Employees.class.php, Events.class.php, and Patrons.class.php.While this does indeed facilitate class management, it also requires that each separate file be madeavailable to any script requiring it, typically through the require_once() statement. Therefore, a scriptrequiring all four classes would require that the following statements be inserted at the beginning:require_once("classes/Books.class.php");require_once("classes/Employees.class.php");require_once("classes/Events.class.php");require_once("classes/Patrons.class.php");Managing class inclusion in this manner can become rather tedious and adds an extra step to thealready often complicated development process. To eliminate this additional task, the concept ofautoloading objects was introduced in <strong>PHP</strong> 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 thescript. 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 the require_once() statements because when a classis invoked for the first time, __autoload() will be called, loading the class according to the commandsdefined in __autoload(). This function can be placed in a global application configuration file, meaningonly that function will need to be made available to the script.■ Note The require_once() function and its siblings were introduced in Chapter 3.SummaryThis chapter introduced object-oriented programming fundamentals, followed by an overview of <strong>PHP</strong>’sbasic object-oriented features, devoting special attention to those enhancements and additions thatwere made available with the <strong>PHP</strong> 5 release.The next chapter expands upon this introductory information, covering topics such as inheritance,interfaces, abstract classes, and more.157

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!