命名空间基础使用实例
/Huyongjian/Controller/User.php
<?php
namespace Huyongjian\Controller;
class User{
public function show(){
echo __METHOD__;
}
}
/Huyongjian/Model/User.php
<?php
namespace Huyongjian\Model;
class User{
public function show(){
echo __METHOD__;
}
}
/index.php
<?php
//导入类文件
include "./Huyongjian/Controller/User.php";
include "./Huyongjian/Model/User.php";
//Huyongjian\Controller命名空间下的User类调用
$controllerUser = new \Huyongjian\Controller\User();
$controllerUser->show();
echo "<hr>";
//Huyongjian\Model命名空间下User类调用
$modelUser = new \Huyongjian\Model\User();
$modelUser->show();
浏览器打印
Huyongjian\Controller\User::show
Huyongjian\Model\User::show
自动加载类
/autoload.php
<?php
spl_autoload_register(function ($class){
$file = str_replace(‘\\‘,‘/‘,$class).‘.php‘;
var_dump($file);
require $file;
});
修改/index.php
<?php
include "autoload.php";
//Huyongjian\Controller命名空间下的User类调用
$controllerUser = new Huyongjian\Controller\User();
$controllerUser->show();
echo "<hr>";
//Huyongjian\Model命名空间下User类调用
$modelUser = new Huyongjian\Model\User();
$modelUser->show()
浏览器打印
Huyongjian\Controller\User::show
Huyongjian\Model\User::show