__autoload()函数spl_autoload_register()函数都是用来自动加载的有什么区别呢?
第一个index.php
加载test1.php
加载test2.php
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php /*** *index.php *加载test1.php *加载test2.php ***/ include 'test1.php'; include 'test2.php'; test1::test11(); echo '<br />'; test2::test22(); |
下面看下test1.php
1 2 3 4 5 6 7 8 9 |
<?php //test1类 class test1{ static function test11(){ echo 'this is '.__METHOD__; } } |
下面看下test2.php
1 2 3 4 5 6 7 8 9 |
<?php //test2类 class test2{ static function test11(){ echo 'this is '.__METHOD__; } } |
修改include为自动加载 如果__autoload 函数加载两次会报致命错误
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php /*** *index.php *自动加载test1.php、test2.php ***/ function __autoload($class){ require __DIR__.'/'.$class.'.php'; } test1::test11(); echo '<br />'; test2::test22(); |
可以自动加载下面来试下spl_autoload_register()函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php /*** *index.php *自动加载test1.php、test2.php ***/ spl_autoload_register('loadd1'); function loadd1($class){ require __DIR__.'/'.$class.'.php'; } test1::test11(); echo '<br />'; test2::test22(); |
spl_autoload_register()函数可以加载多次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php /*** *index.php *自动加载test1.php、test2.php ***/ spl_autoload_register('loadd1'); spl_autoload_register('loadd2'); function loadd1($class){ require __DIR__.'/'.$class.'.php'; } function loadd2($class){ require __DIR__.'/'.$class.'.php'; } test1::test11(); echo '<br />'; test2::test22(); |