Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Autoload class files - PHP Code Bank


Autoload class files
A quick and easy function that saves tons of time, in big sites atleast.
                <?php

/**
 * This function catches all missing classes, and includes a file of choice. Most times you want it to include a file named as the class name.
 **/

// define BASE_PATH constant as the.. base path.

  function __autoload($class)
  {
      $file = str_replace('_','/',$class).'.php';  // In this case it replaces all underlines in the class name with a forward slash.
      require_once(BASE_PATH.'/includes/'.$file); // Here you see that the first part of the class name then gets parsed as a directory beneth includes folder.
  }

// Short explanation: Class Security_Common is then supposed to be located in /includes/Security/Common.php

?>
            
Comments
ghost's avatar
ghost 15 years ago

Handy. Gotta love PHP 5.

ghost's avatar
ghost 15 years ago

Oh yes, i just love the OOP improvements in PHP 5, it's like OOP didn't even exist in PHP 4 :o