on Tips

Autoload your classes in PHP

15 comments
code
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn’t been defined yet.

This is how it works in action. We will create two classes. So create Image.php file and paste this in:

<?php
  class Image {
      
      function __construct() {
          echo 'Class Image loaded successfully <br />';
      }

  }
?>

Now create Test.php file and paste this in:

<?php
  class Test {
      
      function __construct() {
          echo 'Class Test working <br />';
      }

  }
?>

Basically, we created 2 simple classes with constructors which echo some text out. Now, create a file index.php and paste this in:

<?php
  function __autoload($class_name) {
      require_once $class_name . '.php';
  }
  
  $a = new Test();
  $b = new Image();
?>

When you run index.php in browser, everything is working fine (assuming all 3 files are in the same folder). Maybe you don’t see a point, but imagine that you have 10 or more classes and have to write require_once as many times.

I will show you how to properly throw exception if you are using PHP 5.3 and above. Chane your index.php to look like this:

<?php
function __autoload($class_name) {
    if(file_exists($class_name . '.php')) {
        require_once($class_name . '.php');    
    } else {
        throw new Exception("Unable to load $class_name.");
    }
}

try {
    $a = new Test();
    $b = new Image();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>

Now, it checks if file exists and throws a proper Exception if it doesn’t.

That’s it. A handy functionality to spare some typing.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



  • Pingback: Tweets that mention Autoload your classes in PHP | CodeForest -- Topsy.com()

  • Mike

    Is there any performance drawbacks in using this?
    Would it be more effective to include each needed class manually?

    • Zvonko

      There is no performance hit. It doesn’t load classes if you don’t use them. At the moment you instantiate a class, it is calling the __autoload function.

  • Hi, you could safely replace the require_once by a require, don’t care about the class is already loaded or not … if it’s already loaded then the autoload won’t be called …

  • Hossein

    In the name of the kind Allah
    Hello,
    And by defining that autoload function in a separate php file and then using bottom code in htaccess we do not even need to copy/paste this autoload function in every php file:

    php_value auto_prepend_file “auto_loader.php”

    which auto_loader.php file includes that autoload function,

    Is this way useful? Or it can hit performance?

    Thank you

  • Ivan Iordanov

    __autoload is deprecated. Use spl_autoload_register instead

    • __autoload is not deprecated (according to PHP documentation). Where did you get that idea?

  • Rob

    Umm I think I might have one better,

    foreach (glob(“includes/classes/class.*.php”) as $filename)
    {
    include_once( $filename );
    }

    Include all your classes just put the files in a dir called classes, then name then class.XYZ.php

    maybe i am missing something…

    • Hi Rob,
      this way you are including ALL classes, even the ones you don’t need at the moment.

      Thanks for your comment

      • Rob

        😉 thanks, but why would you write a class and not use it?

        sorry had to ask….

        No I understand what are you doing and its pretty interesting. This page has been bookmarked for later control-c control-v ing. 🙂

  • Jos Esteves-Pereira

    I think that you assume that each class is inside a file whose name is the class name plus ‘.php’. Right?
    More, you assume that the class name is exactly written the same way the file name (before dot and extension).
    Example: class Costumer might be inside Costumer.php
    If it’s not always the case, your use of __autolaod seems tio me that doesn’t work.
    Even more if you have more then one class in one file…

    • Of course. If you follow Zend Class Naming Convention that is exactly how your classes and files should be named.

  • Pingback: PHP Autoloading and throwing exception | barrylavides()

  • Bayu Putra

    Thanks for your tutorial, i can understand autoload clearly now.