面向对象(二)类的自动加载

spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] ) : bool

 spl_autoload_register() 函数可以注册任意数量的自动加载器,当使用尚未被定义的类(class)和接口(interface)时自动去加载。

不再建议使用 __autoload() 函数,在以后的版本中它可能被弃用。

function my_autoloader($class) {
    include $class . '.class.php';
}

spl_autoload_register('my_autoloader');

// 或者,自 PHP 5.3.0 起可以使用一个匿名函数
spl_autoload_register(function ($class) {
    include $class . '.class.php';
});

$obj = new Person();
echo $obj->name;

2、本例尝试加载接口 ITest。 

spl_autoload_register(function ($name) {
    var_dump($name);
});

class Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/

3、自动加载在 PHP 5.3.0+ 中的异常处理,本例抛出一个异常并在 try/catch 语句块中演示。

spl_autoload_register(function ($name) {
    echo "Want to load $name.\n";
    throw new Exception("Unable to load $name.");
});

try {
    $obj = new NonLoadableClass();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
/*
Want to load NonLoadableClass.
Unable to load NonLoadableClass.
*/

猜你喜欢

转载自blog.csdn.net/hrbsfdxzhq01/article/details/88871064
今日推荐