在看到某些框架的时候,我会发现,其中有spl_autoload_register和autoload等一系列的关于spl注册的机制。
尤其在一些面向对象的编程当中,你会很明显的看到。
简单说来这些的用法就是方面自动载入你的类,在项目比较庞大的时候比较会用到。
多数应用的情况如下。
正常情况的一般开发是这样的。
text1.php
class Text1
{
static function show()
{
echo "this is Text1.show";
}
}
text2.php
class Text2
{
static function show()
{
echo "this is Text2.show";
}
}
假设你在同一目录的话
include("text1.php");
include("text2.php");
Text1::show();
Text2::show();
运行结果如下:
this is Text1.showthis is Text2.show
刚才我说了随着项目的扩大,和类的增多,每一个都这样写太麻烦了。也容易漏掉
所以会用到__autoload()方法。
如下:index.php
//include("text1.php");
//include("text1.php");
function __autoload($cls)
{
var_dump($cls);
require_once($cls.'.php');
echo "this is function named autoload";
}
Text1::show();
Text2::show();
__autoload()回自动加载这个类,并且用到了require_once,这样就方便了很多。
结果如下
string 'Text1' (length=5)
this is function named autoloadthis is Text1.show
string 'Text2' (length=5)
this is function named autoloadthis is Text2.show
不过有时候我们设计类的时候,可能有一个主类。
那么我们想通过这样有没有办法来做,
这就需要我们使用spl_autoload_register
把autoload这个函数注册进去。
另外写一个textMain.php
/**
*@descripton: 学习spl_autoload_register
将函数注册到SPL __autoload函数栈中。如果该栈中的函数尚未激活,则激活它们。
如果在你的程序中已经实现了__autoload函数,它必须显式注册到__autoload栈中。
因为 spl_autoload_register()函数会将Zend Engine中的__autoload函数取代为spl_autoload()或spl_autoload_call()。
*/
class TextMain
{
static function run()
{
spl_autoload_register('TextMain::autoload');
echo "this is TextMain.show";
}
static function autoload($cls)
{
var_dump($cls);
require_once($cls.'.php');
//echo "this is function named autoload";
}
}
index.php
require_once("textMain.php");
function __autoload($cls)
{
var_dump($cls);
require_once($cls.'.php');
echo "this is function named autoload";
}
TextMain::run();
Text1::show();
Text2::show();
得到的结果:
this is TextMain.show
string 'Text1' (length=5)
this is Text1.show
string 'Text2' (length=5)
this is Text2.show
虽然我们在index.php中有autoload但是仍然没有执行autoload这句话,说明我们的spl_autoload_register中的autoload方法覆盖了。
从手册上我们看到
因为 spl_autoload_register()函数会将Zend Engine中的__autoload函数取代为spl_autoload()或spl_autoload_call()。
就是说一旦你使用了这个函数,那么autoload将被取代。
(2014年4月4日12:08:57)