Overloading and Object-Oriented Programming with PHP 5 - _ _autoload()
(Page 4 of 4 )
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:
function _ _autoload($classname) {
$filename = str_replace("_","/", $classname).
'.php';
include_once $filename;
}
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.
| 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. |
|
This article is excerpted from chapter two of the book Advanced PHP Programming, written by George Schlossnagle (Sams; ISBN: 0672325616). Check it out today at your favorite bookstore. Buy this book now.
|
|