__autoload和spl_autoload_register()
来源:互联网 发布:omega7 知乎 编辑:程序博客网 时间:2024/05/19 17:56
- __autoload()函数
- test.php
- <?php
- function __autoload( $class ) {
- $file = $class . '.class.php';
- if ( is_file($file) ) {
- require_once($file);
- }
- }
- $obj = new test();
- $obj->index();
- ?>
- test.class.php
- <?php
- class test{
- function index(){
- echo 'test.class.php的test类的index方法被调用';
- }
- }
- ?>
- 在面向对象中这种方法经常使用,可以避免书写过多的引用文件,同时也使整个系统更加灵活。
- spl_autoload_register()函数
- <?php
- function example( $class ) {
- $file = $class . '.class.php';
- if ( is_file($file) ) {
- require_once($file);
- }
- }
- spl_autoload_register( 'example' );
- $obj = new test();
- $obj->index();
- ?>
- example不会像__autoload自动触发,spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行example()。
- 静态方法的例子
- <?php
- class StaticTest{
- static public function example( $class ) {
- $file = $class . '.class.php';
- if ( is_file($file) ) {
- require_once($file);
- }
- }
- }
- spl_autoload_register(array('StaticTest','example'));
- //spl_autoload_register('StaticTest::example');
- $obj = new test();
- $obj->index();
- ?>
阅读全文