__autoload in PHP 5

-

Introduction

When writing PHP you often don’t keep all the code in one .php file. Instead you make multiple .php files and then just load the files individually, now what if you don’t always need all those external files to be included every time?

__autoload makes it possible (using naming conventions) to load files only when they are needed. Now sometimes there may come a time when a script tries to include an external script more than once (this would throw an error) therefore the __autoload magic method will not include a file again if the file has already been loaded

 

Using __Autoload

When using the __autoload magic method you must use strict naming conventions. If you are instantiating a class, the class name must match the name of the .php file that you want to include. To __autoload function might look something like: 

<?php
  function __autoload($className) {
    include $class_name . '.php';
  }
  $Object = new WebDeveloper();
?>

The above code will automatically call the __autoload magic method because there is no ‘WebDeveloper’ class included within the script. The __autoload will therefore look for a WebDeveloper.php file and include it within the script before throwing an error.  

Your comments.