【问题标题】:Does not respond as expected没有按预期响应
【发布时间】:2014-09-06 03:42:39
【问题描述】:

我在控制器的开头有以下代码(我正在使用 Yii):

protected function beforeAction($action = null)
{
    switch ($this->action->id)
    {
        case 'Images':
            // Do something
            break;

            // ...
    }

    if ($this->action->id == 'index' || $this->action->id == 'videos')
    {
        // Do something else
    }

    return true;
}

public function actionIndex()
{
    // ...
}

public function actionVideos()
{
    // ...
}

public function actionImages()
{
    // ...
}

如您所见,if 语句和 switch 语句都使用 $this->action->id,它返回动作名称。

在switch语句中,它只接受“Images”,大写字母的问题,而$this->action->id返回一个小写字符串。

我什至尝试编写另一个 if 语句而不是 switch - 但同样的问题。

另外,尝试检查字符串 $this->action->id 返回 actionImages() 和其他 - 都是小写。

【问题讨论】:

    标签: php yii controller action


    【解决方案1】:

    你可以用小写写你的case语句 要么 你可以像这样使用 ucfirst($this->action->id)

    protected function beforeAction($action = null)
    {
        $var=ucfirst($this->action->id);
        switch ($var)
        {
            case 'Images':
                // Do something
                break;
    
                // ...
        }
    
        if ($this->action->id == 'index' || $this->action->id == 'videos')
        {
            // Do something else
        }
    
        return true;
    }
    
    public function actionIndex()
    {
        // ...
    }
    
    public function actionVideos()
    {
        // ...
    }
    
    public function actionImages()
    {
        // ...
    }
    

    【讨论】:

    • 谢谢,原来是我的错。
    【解决方案2】:

    改变字母的大小写 检查strtolower()ucfirst() 方法

    【讨论】:

      【解决方案3】:

      尝试define 字符串,看看它们在两个语句中是否匹配。还要检查action->id 的来源及其返回的内容。

      【讨论】:

        猜你喜欢
        • 2014-10-31
        • 2016-02-27
        • 2019-11-26
        • 2018-11-23
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多