spl_autoload_register() 是 php 一个自动加载类库的方法;
其属于 autoload 家族的一个成员。详细的介绍就不多赘述了,直接传送门
直接上代码
代码目录:WkTest
入口文件 <index.php>
<?php
$url = explode( '/', strstr( $_SERVER['PHP_SELF'], 'index.php') );
$module = isset( $url[1] )?$url[1]:'Wk';
$action = isset( $url[2] )?$url[2]:'Show';
function loadClass($class) {
$file = realpath(__DIR__).'/'.$class.'.class.php';
if( !is_file( $file ) ){
header( 'HTTP/1.1 404 Not Found' );
// echo $class.' is not found ';
exit();
}else{
include $file;
}
}
spl_autoload_register('loadClass');
if( !class_exists( $module ) || !method_exists( $module, $action ) ){
header( 'HTTP/1.1 404 Not Found' );
// echo $module.'/'.$action.' is not found ';
exit();
}
$obj = new $module;
$obj->$action();
exit();
?>
类文件
Wk.class.php
<?php
class Wk {
function __construct() {
// echo "Wk __construct() \r\n";
}
static public function show() {
$param = $_GET;
$message = isset( $param['message'] )?$param['message']:'';
echo $message."\r\n<br>Hello, World!";
}
}
?>
完成,直接访问
http://localhost/WkTest/index.php
http://localhost/WkTest/index.php/Wk/Show?message=“wk”
是不是超级简单,如果要支持更复杂的逻辑,就要自己多实践了