PHP/Class/ autoload

Материал из Web эксперт
Перейти к: навигация, поиск

__autoload() function automatically includes a class file.

 
function __autoload($classname) 
{ 
    require_once("/includes/classes/$classname.inc.php"); 
}



__autoload( ) is called whenever you try to create an object of a class that hasn"t been defined

 
<?
    function __autoload($Class) {
            print "Bar class name: $Class!\n";
            include "barclass.php";
    }
    $foo = new Bar;
    $foo->wombat( );
?>



Automatically Loading Include Files with ___autoload()

 
<?php
function ___autoload ($class) {
  $file = "$class.inc.php";
  include_once( $file );
}
$test = new YourClassName();
?>



Creating an __autoload() Function

 
<?php
function __autoload($classname) {
    require_once "class-{$classname}.php";
}
$mydisk = new cd();
?>



Using the __autoload() Function

 
<?php
     function __autoload($class) {
          $files = array("MyClass" => "/path/to/myClass.class.php",
                         "anotherClass" => "/path/to/anotherClass.class.php");
          if(!isset($files[$class])) return;
          require_once($files[$class]);
     }
     $a = new MyClass;
     $b = new anotherClass;
?>