search for in the  
<The BasicsConstructors and Destructors>
Last updated: Thu, 19 May 2005

Autoloading Objects

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 which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

Note: Exceptions thrown in __autoload function cannot be caught in the catch block and results in a fatal error.

Example 19-5. Autoload example

This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.

<?php
function __autoload($class_name) {
   require_once
$class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2();
?>



User Contributed Notes
Autoloading Objects
scott at webscott dot com
04-May-2005 08:40
__autoload() seems to work when saving objects as session variables as well:

classLoader.php
<?php
function __autoload($className) {
  require_once(
"$className.php");
}
?>

testClass.php
<?php
class testClass {
  function
__construct($propValue) {
  
$this->prop1 = $propValue;
  }

  function
showProp() {
   return
$this->prop1;
  }
}
?>

page1.php
<?php
require_once('classLoader.php');
session_start();
$_SESSION['testObj'] = new testClass('foo');
echo
'<a href="page2.php">Go to page 2</a>';
?>

page2.php
<?php
require_once('classLoader.php');
session_start();
echo
$_SESSION['testObj']->showProp(); // displays foo
?>

Works with multiple session objects as well.  Tested on a Win2k/IIS machine.
erikzoltan NOSPAM at comcast dot net
06-Apr-2005 10:41
When using __autoload you'll have one class in each file.  I have developed the habit of placing a UML class diagram at the top of each file.  It's extremely helpful when you start to work with a large number of classes, especially if you're part of a team.  And it's easy to do. 

<?php

/*
|--------------------------------|
| MyExample : SomethingElse      |
|--------------------------------|
| +$FirstProperty                |
| +$SecondProperty: array        |
| -$ThirdProperty                |
|--------------------------------|
| +new MyExample()              |
| #ClassMethod($a,$b,$c): number |
| +DoSomething()                |
| -SomethingElse()              |
|--------------------------------|
*/

class MyExample extends SomethingElse
{
   public
$FirstProperty;
   public
$SecondProperty = array();
   private
$ThirdProperty;
   public
__constructor()
   {
   }
   public static function
ClassMethod($a, $b, $c)
   {
       return
$a+$b+$c;
   }
   public function
DoSomething()
   {
   }
   private function
SomethingElse()
   {
   }
}
?>

Of course you have to maintain the UML comments along with your classes.  (I'm planning to use reflection to automate this process in the future so that issue will soon disappear.)
El Lobo
17-Mar-2005 08:10
function autoloadwrapper($parameter='',$register=false) {
  static $function='default_function';
  if( $register ){
   $function=$parameter;
   return true;
  }
  if( ! is_array($parameter) ){
   $param[]=$parameter;
  }else{
   $param&=$parameter;
  }
  if( function_exists( $function ) ){
   return @call_user_func_array( $function,$param );
  }else{
   $methode=explode("::",$function);
   return @call_user_func_array( $methode,$param );
  }
}

function __autoload($class_name) {
  return autoloadwrapper( $class_name );
}

Simple hack to switch between different __autoload-functions.
trini0
01-Feb-2005 11:04
Be careful with using that eval() trick within __autoload().
If you use reflection in your code, the so called trick,
*can* provide ill side effects.
For example ->
$reflection = new reflectionClass('some_class');
if (FALSE === $reflection->isSubClassOf('another_class'))
{
   throw new Exception('Class "some_class" must extend base class "another_class"');
}

If the real class "another_class" doesnt exist at the time, or "some_class" doesn't extend "another_class", with the reflection test, the so called eval() trick, creates a dummy "another_class",
thereby making the reflection test useless...
petyo()architect . bg
30-Jan-2005 04:27
The following function may be useful if you want to simulate namespaces and autoloading behavior:

define ("CLASS_ROOT", '/classes/');
function __autoload ($className)
{
   require_once CLASS_ROOT.str_replace('_', '/', $className).'.class.php';
}

Then you will just have to use the folder structure and name the classes accordingly. If you want to have a class named Page, which will be in the pseudo namespace System.Web.UI, create a directory named System in /classes, then create Web, then UI, then name the class System_Web_UI_Page. Kind of long to type if you don't have autocomplete, but at least you will not have to manage the loading of all the classes' definitions.
thomas dot revell at uwe dot ac dot uk
27-Jan-2005 09:31
If you want to throw an exception if a class isn't defined yet, use class_exists ():

<?php
// See if the class is defined
if (!class_exists ($className, false)) {
   throw new
Exception ("Class $className is not defined.");
}
?>

The second parameter indicates whether or not the __autoload () function should be called before checking for the class's existence.
Jami Pekkanen
17-Jan-2005 07:27
Autoloading can be abused to simulate C++-style templates:

<?php
function __autoload($className)
{
      
$names = explode('__', $className, 2);
       if(
count($names) != 2) return;

       eval(
      
"class $className extends {$names[0]}
       {
               public static function getTemplateValue()
               {
                       return {$names[1]};
               }
       }"
      
);
}

class
Dummy {}
echo
Dummy__HelloWorld::getTemplateValue()."\n"; // HelloWorld
$bye = new Dummy__ByeBye();
echo
$bye->getTemplateValue()."\n"; // ByeBye
?>

Also a great way to confuse anyone trying to read/maintain your code.
smith at backendmedia dot com
04-Jan-2005 10:45
It seems that __autoload() works both for classes and interfaces.
nhartkamp at eljakim dot N0SP4M dot nl
11-Dec-2004 12:14
The following might provide a good work-around for throwing exceptions from the __autoload function when a file containing the correct class doesn't exists.

function __autoload ($class_name) {
  $file = 'system/objects/' . $class_name . '.inc.php';
  if (!file_exists ($file)) {
   return eval ("class $class_name {" .
                 "  function $class_name () {" .
                 "    throw new Exception ();" .
                 "  }" .
                 "}");
  }
  require_once ($file);
}

Cheers,
Nolan
ernest at vogelsinger dot at
28-Nov-2004 05:43
Note that it is not possible to catch an exception thrown from within __autoload.

See also bug report #26193 (http://bugs.php.net/bug.php?id=26193) - this states "Won't fix", so read it before you holler.

<The BasicsConstructors and Destructors>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 18:35:34 2005 EDT