AJAX聊天命令 - 如果命令不存在,则回显错误

时间:2013-06-20 19:10:42

标签: php function oop

所以我有这个命令处理:

$ message =输入的消息。

    public function handleCommands($message, $username)
    {
        //Variables we're going to use
        $space = strpos($message, ' '); # The first space.
        $command = trim(substr($message, 1, $space)); # The command after the slash
        $name = substr($message, $space + 1); # The name after the command.


        switch ($command)
        {
            case 'ban':
                $this->ban($name, $username);
            break;

            case 'prune':
                $this->prune($username);
            break;

            case '':
                echo 'Please use a command!';
            break;

            case 'test':
                try
                {
                    $this->test($name);
                }
                catch (exception $r)
                {
                    echo $r->getMessage();
                }
            break;
        }
    }

这基本上会检查命令。

$ command =斜杠后面输入的单词(“/”)。

你能看到

吗?
case '':

这基本上检查斜杠后是否没有命令。

问题: 我希望系统检查,如果命令中存在该命令。

例如:

用户写道:

/你好

但是这个命令不存在,考虑到我们只有案例'禁令',案例'修剪',案例'测试'和案例''。

没有'hello'的情况,因此会抛出错误。 是否有一种功能可以做这种事情?我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

我相信您所寻找的是default:案例。

示例:

<?php
switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
       echo "i is not equal to 0, 1 or 2";
}
?>

修改: 已修复的问题的固定版本:http://privatepaste.com/bd34e7e63b

答案 1 :(得分:1)

使用案例默认值:

    switch ($command)
    {
        case 'ban':
            $this->ban($name, $username);
        break;

        case 'prune':
            $this->prune($username);
        break;

        case '':
            echo 'Please use a command!';
        break;

        case 'test':
            try
            {
                $this->test($name);
            }
            catch (exception $r)
            {
                echo $r->getMessage();
            }
        break;

        default:
            echo "That command does not exist.";
    }