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


class ClassLoader
  //specify list of the default folders where you
  //want always look for classes first
  private static $default = array(

  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;
    return $exists;

function __autoload($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, JAVA, Spring, Hibernate, AngularJs, Backbone, MongoDB, Oracle. CTO and Co-Founder of Homeadnet.com

More Posts

Follow Me:

Tagged with: