HomePHP Page 4 - Overloading and Object-Oriented Programming with PHP 5
_ _autoload() - PHP
Last week, we discussed design patterns and polymorphism. This week, we examine overloading and more. This article, the last of four parts, is excerpted from chapter two of the book Advanced PHP Programming, written by George Schlossnagle (Sams; ISBN: 0672325616).
The final magic overloading operator we will talk about in this chapter is _ _autoload(). _ _autoload() provides a global callback to be executed when you try to instantiate a nonexistent class. If you have a packaging system where class names correspond to the files they are defined in, you can use _ _autoload() to do just-in-time inclusion of class libraries.
If a class you are trying to instantiate is undefined, your _ _autoload() function will be called, and the instantiation will be tried again. If the instantiation fails the second time, you will get the standard fatal error that results from a failed instantiation attempt.
If you use a packaging system such as PEAR, where the class Net_Telnet is defined in the file Net/Telnet.php, the following _ _autoload() function would include it on-the-fly:
All you need to do is replace each _ with / to translate the class name into a filename, append .php, and include that file. Then if you execute the following without having required any files, you will be successful, as long as there is a Net/Telnet.php in your include path:
<?php
$telnet = new Net_Telnet;
? >
Further Reading
There are a great number of excellent books on OO programming techniques and design patterns. These are by far my two favorite design pattern books:
Design Patterns (by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides). This is called the "Gang of Four" book, after its four authors. This is the ultimate classic on patterns.
Patterns of Enterprise Application Architecture (by Martin Fowler). Fowler is an incredibly experienced fellow, and this book is an insightful and extremely practical approach to design patterns, particularly on the Web.
Neither of these books focuses on PHP, but if you're willing to wade through C++, C#, and Python, they are well worth the effort.