Today I’m going to present a function that most of the PHP community doesn’t know about. It falls under the “magic functions”, was included in PHP5, but needs to be defined.
In medium-scale projects where we have more than a few files, it’s almost certain that we’ll be using classes and including them from external files.
<br></br><br></br>
This is a typical example of a simple/complex application. We include our file on every page where we’ll need a database connection and on each of them we instantiate our object.
We can continue along this line of thinking: for a project to work it will also need a class to manage users, another to manage templates — and for the more demanding, one for caching as well.
We’ll most likely use a single page, commonly called kernel or global, that will include all of this for us on every page (or the single page) of our project.
But everything becomes simpler if we make use of this function. Imagine the following piece of code, which literally represents what our index would look like:
<br></br><br></br>
The capabilities of this function should be evident by now. When we create a new object, if the interpreter can’t find the defined class it calls the __autoload function and passes the class name as an argument. Everything else is left to our imagination.
This function is already used in top frameworks like codeigniter, cakephp, and the recent, acclaimed Zend Framework. Furthermore, it has been partially proven that using __autoload is approximately ~3.7x more efficient than directly using require_once.
Here’s one last example of how I use this function in some applications, making my code more readable and incorporating an error log. When I call a class, each ___ (underscore) represents one folder level deeper, making it easy to organize modules and classes.
<br></br><br></br>