This has to be one of my favorite time savers.
If you’re an experienced PHP programmer you separate your common methods (aka: functions) into Class files. Over time, this can become an organizational nightmare if your application became large.
There is an easy fix for this using PHP’s spl_autoload_register. This not so well known function is called each time a Class is instantiated. We can register our own functions to process the name of the Class being called, and easily include that Class in real-time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php /* Register 'myAutoloader' function with the spl_autoload_register */ spl_autoload_register('myAutoloader'); /* Load the PHP file in this directory that has the same name as the new Class being called. */ function myAutoloader($className) { $file = __DIR__ . '/' . $className . '.php'; if (file_exists($file)) { include($file); } } ?> |
Using this approach could not be any simpler.
1 2 3 4 5 6 7 |
<?php $myObject = new myClass(); // auto-load class $foo = $myObject->someMethod(); // use class in real-time ?> |
Assuming you have included the SPL_AUTOLOADER scripts first, instantiating myClass() will auto-magically load the Class file myClass.php from the defined directory set in the myAutoloader() function.
It’s so simple you’ll ask yourself why you have not used this in the past.