Automatically Loading Include Files with ___autoload()

In a large project, code files tend to fill up with calls to include_once(). Very often, you will find that you are loading many files unnecessarily as you copy around amended source files. By the same token, you waste time adding include_once() calls to class files, only to run the script and discover that more files need including. PHP 5 provides the built-in __autoload() function, which is automatically called whenever you try to instantiate an nonexistent class. __autoload() is passed a string variable representing the class name that was not found. You can then use this string to include a source file:

 <?php function ___autoload ($class) { $file = "$class.inc.php"; include_once( $file ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.