6.12. Class Autoloading

When you attempt to use a class you haven't defined, PHP generates a fatal error, of course. The obvious solution to this situation involves adding a class definition, probably by issuing an include statement. After all, you should know which classes a script uses. However, PHP offers class autoloading, which may save programming time. When you attempt to use a class PHP does not recognize, it looks for a global function named __autoload. If it exists, PHP calls it with a single parameter, the name of the class. Inside the function, you may take the necessary steps to create the class.

Listing 6.15 demonstrates the use of __autoload. It uses a simple scheme that assumes files in the current directory match each class. ...

Get Core PHP Programming, 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.