spl_autoload_register()自动加载你的php类,不用require_once啦。
点击 11221 创建时间 2013-08-10 11:51:21
spl_autoload_register()
通过声名一个函数,用来自动加载一个类。当你实例化时,当前上下文中没有找到这个类,他就会通过注册的函数来加载你所需要的类。是不是很方便呢?对于要加载多个类的的程序,写代码的时间大大节省了。
我们来做一个例子:
api/client.php
<?php
namespace api;
class client{
public function call()
{
echo "call...";
}
}
api/server.php
<?php
namespace api;
class server{
public function accept(){
echo "accepting....";
}
}
api/test.php
<?php
function autoload_class ($className) {
include(__DIR__ . "/" . $className . ".php");
}
spl_autoload_register("autoload_class");
use api\client;
$c = new client();
$c->call();
use api\server;
$s = new server();
$s->accept();
输出:
call...accepting....
按以前的方式,我们需要写
<?php
require_once "api/client.php";
require_once "api/client.php";
如果类多,需要加载很多次,特别麻烦。建议不要用__autoload(),这个函数以后可能会被弃用。
上一篇: git did not exit cleanly (exit code 128)的解决办法
下一篇: rong framework 1.0 发布了