PHP自动加载 魔术方法 __autoload()
魔术方法,当实例化的类找不到时,会自动调用此方法
__autoload()在php7.2中被废弃
但也出现了新的函数
spl_autoload_register('自动加载方法名');
举例:
Test.php
<?php
class Test
{
public function index()
{
echo '测试类';
}
}
class Test2
{
function index()
{
echo 'Test2方法';
}
}
Load.php
<?php
function myLoad($classname)
{
$classpath='./'.$classname.'.php';
//判断文件是否存在 存在则自动引入
if (file_exists($classpath)) {
require_once $classpath;
}
}
spl_autoload_register('myLoad');
$test=new Test();
$test->index();
$test2 = new Test2();
$test2->index();
访问load文件成功触发sql方法
自动加载了两个同级类Test与Test2
分别输出测试类与 Test2方法
# 由浅入深 接下来我们加上命名空间
再来看定义 也就是被调用的其他类
namespace Controller;(就好像说这是我居住的目录一样)
<?php
//定义所在空间
namespace Controller;
class Test
{
public function index()
{
echo '测试类';
}
}
在入口文件自动加载时写上使用这个命名空间就好了
use Controller\要使用的类名;
想调用哪个类只需要use 一下它家\它的名字就好
这就是使用这个命名空间(入口文件Load)
<?php
use Controller\Test;
spl_autoload_register(function ($className) {
require $className . '.php';
});
$test=new Test();
$test->index();
$test2 = new Test2();
$test2->index();
解释:
用法跟autoload差不多
当类不存在时触发spl_autoload_register()方法
此方法绑定了myLoad方法,执行myLoad方法
相当于autoload改为我们自己定义的方法了
官方推荐用spl_autoload_register()替代__autoload()
区别:
__autoload方法只能定义一次
而spl可以多次定义
而官方也建议使用sql函数了
评论已关闭