__autoload() 实现类的自动加载
好处:避免每个php脚本开头include或require一堆类文件
使用:__autoload()传入类名
当实例化对象,会自动引入类
例子
index.php 入口文件 MyClass1.php被自动引入的类文件
index.php
function __autoload($class_name) { $classFile = $class_name.'.php'; if(is_file($classFile) && file_exists($classFile)){ require_once $classFile; } } //new对象时会自动执行 require_once(MyClass1.php); $obj = new MyClass1(); //$obj2 = new MyClass2();
MyClass1.php 就写个空类即可
<?php class MyClass1 { }
手册推荐使用spl_autoload_register来实现,即自己写autoload函数,然后用spl_autoload_register来注册autoload函数
<?php function loader($class) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } spl_autoload_register('loader'); $a = new A(); ?>
spl_autoload_register还可以注册类方法
<?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(); ?>
综合一下
if(function_exists('spl_autoload_register')) { spl_autoload_register(array('core', 'autoload')); } else { function __autoload($class) { return core::autoload($class); } }