Undoubtedly, the release of PHP 5 has had a remarkable impact on the way that object-oriented applications are developed nowadays. This highly-improved model has provided PHP programmers with features that were only present in mature object-based languages, like Java and C++, but now, fortunately for you and me, they are generously offered by this powerful server-side scripting language.

Loading classes automatically: taking a look at the “__autoload()” PHP 5 magic function

<?php

class ClassLoader
{
  //specify list of the default folders where you
  //want always look for classes first
  private static $default = array(
    'folder/classes/',
    'folder/classes/.../',
  );  

  public static function load_class($class_name)
  {
    $exists = FALSE;

    // iterate through the class directories
    //until a match is found
    foreach (self::$default as $dir)
    {
      if (file_exists(($include=$dir.$class_name.'.php')))
      {
        require_once $include;
        $exists = TRUE;
        break;
      }
    }
    return $exists;
  }
}

function __autoload($class_name)
{
  ClassLoader::load_class($class_name);
}

Save content above into the file ClassLoader.php and make sure this file is always included at the top of your program. Enjoy!

 

Dima Svirid

Software architect. Ajax/Javascript, HTML5, Android, iPhone/iPad, JAVA, PHP, Cold Fusion, SQL, Air, Flash, Open source software, Frameworks

More Posts

Follow Me:

Thank you! Useful article

Thank you for reading! If you find this article useful and interesting, please click on one of our sponsor links below as a little appreciation and support.
Happy coding!

close [x]
Tagged with:
 

Leave a Reply