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).
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:
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.
blog comments powered by Disqus |