您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

如何更优雅的写这段代码

2025/1/17 10:01:41发布21次查看
'profile', 3 => 'login', 7 => 'show', 9 => 'update', 11 => 'stop', 13 => 'start', 15 => 'remove',);//判断命令对应的动作是否存在if (!array_key_exists($command, $actions)) throw new exception('404');$control = new app();$method = 'on' . ucfirst($actions[$command]);//判断类里面是否存在该函数if (!method_exists($control, $method)) throw new exception('404');

回复内容: 'profile', 3 => 'login', 7 => 'show', 9 => 'update', 11 => 'stop', 13 => 'start', 15 => 'remove',);//判断命令对应的动作是否存在if (!array_key_exists($command, $actions)) throw new exception('404');$control = new app();$method = 'on' . ucfirst($actions[$command]);//判断类里面是否存在该函数if (!method_exists($control, $method)) throw new exception('404');

凭感觉猜测题主是需要一个简洁的分发,那么可以考虑
phpclass app { protected static $actions = [ 1 => 'onprofile', 2 => 'onlogin', //... ]; public function run($command) { if (!isset(self::$actions[$command])) { throw ...; } $callback = [$this, self::$actions[$command]]; if (!is_callable($callback)) { throw ...; } call_user_func($callable); }}//index.phpnew app()->run($_get['command']);
先指出一点错误, 一般检测类似controller这种类方法是否可以被调用, 需要使用is_callable而不是method_exists, 前者检查方法是否可以被调用(存在且公开), 后者只是单纯检查方法是否存在。
class notfoundexception extends exception {}$command = $_get['command'] ?: false;$actions = array( 'profile', 'login', 'show', 'update', 'stop', 'start', 'remove',);//判断命令对应的动作是否存在if ( ! in_array($command, $actions)) throw new notfoundexception();$control = new app();$method = 'on' . ucfirst($command);//判断类里面是否存在该函数if ( ! is_callable(array($control, $method))) throw new notfoundexception();
看看 flight 框架 也是另外一种思路
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product