之前写的文章中有写PHP的autoLoad自动加载机制,但是目前的框架中用的却是SPL autoload机制。
什么是spl autoload?spl autolaod机制是什么?
SPL autoload机制的实现是通过将函数指针autoload_func指向自己实现的具有自动装载功能的函数来实现的。SPL有两个不同的函数 spl_autoload, spl_autoload_call,通过将autoload_func指向这两个不同的函数地址来实现不同的自动加载机制。
这里要讲一个函数spl_autoload_register(),这个函数与__autoload有与曲同工之妙,看个简单的例子:
新建文件Person.php
<?php class Person { var $name, $age; function __construct ($name, $age) { $this->name = $name; $this->age = $age; } } ?>
新建文件demo.php
<?php function loadprint( $class ) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } spl_autoload_register('loadprint'); $person = new Person("Altair", 6); var_dump ($person); ?>
看看是不是也实现了autoload的功能
还有一种方式在zend fromwork中使用的
<?php class test{ public static function loadprint( $class ) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } } spl_autoload_register(array('test','loadprint')); //另一种写法:spl_autoload_register( "test::loadprint" ); $person = new Person("Altair", 6); var_dump ($person); }