• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

如何更优雅的写这段代码

php 搞代码 3年前 (2022-01-25) 20次浏览 已收录 0个评论
文章目录[隐藏]
<code><?php$command = (int)$_GET['command'];$actions = array(    1 => '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');</code>

回复内容:

<code><?php$command = (int)$_GET['command'];$actions = array(    1 => '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]);//判断类里面是否存在<mark style="color:transparent">来4源gaodaimacom搞#代%码*网</mark><code>搞代gaodaima码</code>该函数if (!method_exists($control, $method)) throw new Exception('404');</code>

凭感觉猜测题主是需要一个简洁的分发,那么可以考虑

<code>php</code><code>class 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']);</code>

先指出一点错误, 一般检测类似controller这种类方法是否可以被调用, 需要使用is_callable而不是method_exists, 前者检查方法是否可以被调用(存在且公开), 后者只是单纯检查方法是否存在。

<code>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();</code>

看看 Flight 框架 也是另外一种思路


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何更优雅的写这段代码
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址