tp5控制器不存在的问题
在tp框架中,不走路由的情况下大驼峰的控制器名会被先转成小写最后把首字母变成大写,如 GetType 最终会被转成Gettype 我看了tp的源码判断控制器是否存在用的class_exists(),但是这个方法不是不区分类名的大小写吗?请大佬帮忙解答
tp中判断控制器是否存在的源码
/ * 实例化(分层)控制器 格式:[模块名/]控制器名
* @access public
* @param string $name 资源地址
* @param string $layer 控制层名称
* @param bool $appendSuffix 是否添加类名后缀
* @param string $empty 空控制器名称
* @return object
* @throws ClassNotFoundException
*/
public function controller($name, $layer = 'controller', $appendSuffix = false, $empty = '')
{
list($module, $class) = $this->parseModuleAndClass($name, $layer, $appendSuffix);
// dump(class_exists("app\index\controller\Gettype")); 返回false
// dump(class_exists('app\index\controller\GetType')); 返回true
if (class_exists($class)) {
return $this->make($class, true);
} elseif ($empty && class_exists($emptyClass = $this->parseClass($module, $layer, $empty, $appendSuffix))) {
return $this->make($emptyClass, true);
}
throw new ClassNotFoundException('class not exists:' . $class, $class);
}

我在tp中的index控制器中测试class_exists()的返回值
<?php
namespace app\index\controller;
use think\facade\Config;
use think\Request;
use think\Controller;
class Index extends Controller
{
public function index()
{
return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V5.1<br/><span style="font-size:30px">12载初心不改(2006-2018) - 你值得信赖的PHP框架</span></p></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="eab4b9f840753f8e7"></think>';
}
public function t()
{
// return $this->fetch();
dump(class_exists("app\index\controller\gettype"));//返回false
dump(class_exists("app\index\controller\GetType"));//返回true
}
}
不在tp框架中使用class_exists()
<?php
namespace app\index\controller;
class GetType
{
}
var_dump(class_exists('app\index\controller\gettype'));//返回true
var_dump(class_exists('app\index\controller\GetType'));//返回true
这个是我在tp5.0中测试的代码 跟我在tp5.1中打印的结果一样
@

官网写的class_exists不区分类名大小写
哪个自动加载什么的我通过debug查看 判断控制器是否存在就被调用了一次 就是我上面问题发的那段代码
@
就是那个用来检测控制器是否存在的逻辑 值在App类下的controller方法中调用了一次,所以控制器不存在不是因为自动加载而进行的判断@
找到原因了,确实是因为class_exists()默认会出触发自动加载的原因
关于 LearnKu
推荐文章: