__autoload自动加载类文件 和spl_autoload_register函数

--------clsdemo.php文件--------
<?php  
class clsdemo {  
    public function show(){  
        echo "test";  
    }  
}  
?> 
---------index.php文件---------
//不需要include require单独引用 php5函数 会在IO文件时有一定的性能消耗 
<?php  
function __autoload($class_name) {  
    require_once $class_name . '.php';  
}  
  
$test  = new clsdemo();  
$test->show();  //显示是test  
?>

---------spl.php文件-----------
<?php  
function loader($class_name) {  
    require_once $class_name . '.php';  
}  
 
spl_load_register('loader');	//自动加载的时候不调用__autoload()而调用自己的函数或类方法
  
$test  = new clsdemo();  
$test->show();  //显示是test  
?>

-----------调用类方法------------
<?php
class Loader
{
    public static function loadClass($class_name)
    {
	require_once $class_name . '.php';  
    }
}

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

?>

猜你喜欢

转载自bosnzt.iteye.com/blog/1606793