As I said in the section that you just read, I'd like to provide you with an example that shows how to eagerly include the previous "User" class by using a stricter object-oriented approach. To accomplish this, I'll code a simple loader class whose main goal will be statically including a specified file into a given script. The complete definition of this brand new loader mechanism, along with a couple of custom exception classes, is shown below. Look at them, please: // create custom FileNotFoundException exception class class FileNotFoundException extends Exception {}
// create custom ClassNotFoundException exception class class ClassNotFoundException extends Exception {}
// define 'Loader' class class Loader {
public static function load($class) { if (class_exists($class, FALSE)) { return; } $file = $class . '.php'; if(!file_exists($file)) { throw new FileNotFoundException('File ' . $file . ' not found.'); } require $file; unset($file); if (!class_exists($class, FALSE)) { eval('class ' . $class . '{}'); throw new ClassNotFoundException('Class ' . $class . ' not found.'); } } } As depicted above, the "Loader" class is comprised of a single static method called "load()," which implements the logic required to include the definition of a specified class into a calling script. Also, I added a couple of exception subclasses to handle more specifically any errors that might arise when performing the inclusion process. So far, so good. At this point, I'm pretty sure that you already grasped the underlying logic of the above "Loader" class, right? Then it's time to build a script that uses this loader module to eagerly include the sample "User" class. Want to see how this will be done? Click on the link that appears below and read the next section.
blog comments powered by Disqus |
|
|
|
|
|
|
|