- __autoload
在PHP中,我们通常将一个类放在一个文件中,当其他的类需要使用某个类时,只需通过include或require将需要使用的类包含进来即可,但是当某个类需要依赖成百上千个或者更多的其他类时,就得有成百上千的include或者require,这时PHP文件就会很臃肿,这时__autoload()就起到作用了
__autoload():魔术方法,当实例化的类找不到时,会自动调用此方法,示例如下:
Test.php
<?php
class Test
{
public function index()
{
echo '测试类';
}
}
LoadTest.php
<?php function __autoload($classname) { $classpath='./'.$classname.'.php'; if (file_exists($classpath)) { require_once $classpath; } } $test=new Test(); $test->index();
输出:测试类
解释:
- 参数$classname为实例化的类名称,此例中就是Test
- 通过__autoload()找不到的类就会自定进行加载,省去了大量的require重复操作
- __autoload()只是在出错失败前多了一次加载所需类的机会,如果__autoload()里还是没找到所需的类,依旧会报错
- __autoload()只能定义一次
注意:PHP7.2之后已经弃用了此魔术方法
Warning This feature has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged.
- spl_autoload_register()
此函数的功能跟__autoload()差不多,都是当实例化当类不存在的时候调用此方法
示例
Test.php
<?php
class Test
{
public function index()
{
echo '测试类';
}
}
LoadTest.php
扫描二维码关注公众号,回复:
5599188 查看本文章
<?php
function myLoad($classname)
{
$classpath='./'.$classname.'.php';
if (file_exists($classpath)) {
require_once $classpath;
}
}
spl_autoload_register('myLoad');
$test=new Test();
$test->index();
输出:测试类
解释:
用法跟__autoload差不多,当类不存在时触发spl_autoload_register()方法,此方法绑定了myLoad方法,执行myLoad方法,相当于__autoload改为我们自己定义的方法了,官方推荐用spl_autoload_register()替代__autoload()
也可以调用静态方法
LoadTest.php
<?php
class LoadTest
{
public static function myLoad($classname)
{
$classpath='./'.$classname.'.php';
if (file_exists($classpath)) {
require_once $classpath;
}
}
}
spl_autoload_register(array('LoadTest','myLoad'));
//spl_autoload_register('LoadTest::myLoad');这两种方法都可以调用静态方法
$test=new Test();
$test->index();