php中spl_autoload_resgiterの使い方

2726 ワード


spl_autoload_register
(PHP 5 >= 5.1.2)
spl_autoload_register —   __autoload()  
  
bool spl_autoload_register ([ callback $autoload_function ] )
      SPL __autoload    。            ,     。
             __autoload  ,        __autoload  。  
spl_autoload_register()    Zend Engine  __autoload     spl_autoload() 
spl_autoload_call()。
  
autoload_function
          。          ,     autoload       
spl_autoload()。
   
        TRUE,      FALSE。
 :SPL Standard PHP Library(  PHP )   。  PHP5        ,       autoload          Iterator    。 SPL autoload             autoload_func                      。SPL         spl_autoload, spl_autoload_call,   autoload_func                        。
  

         A.php,          A  :

view plaincopy to clipboardprint?


<?php
class A
{
public function __construct()
{
echo 'Got it.';
}
}
       index.php       A,       

view plaincopy to clipboardprint?
<?php  
require('A.php');  
$a = new A();

         ,      index.php         A,       ,          require  ,           。


   php5     ,           。 php5 ,                __autoload  ,          __autoload    php     ,               。

          ,index.php     :

view plaincopy to clipboardprint?


<?php
function __autoload($class)
{
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}

$a = new A();
            ,__autoload   include_path        ,             __autoload      。

  ,               __autoload,           (     ),       spl_autoload_register        autoload  。        :
bool spl_autoload_register ( [callback $autoload_function] )

            :

view plaincopy to clipboardprint?


<?php
function loader($class)
{
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}

spl_autoload_register('loader');

$a = new A();
            ,   php            __autoload             loader 。     ,           :

view plaincopy to clipboardprint?
<?php  
class Loader  
{  
public static function loadClass($class)  
{  
$file = $class . '.php';  
if (is_file($file)) {  
require_once($file);  
}  
}  
}  

spl_autoload_register(array('Loader', 'loadClass'));  

$a = new A();