Switch and if语句返回第一个case条件,不管它是否为真


Switch and if statement returns the first case condition regardless if it is true or not

我正在研究一个项目,我已经配置为使用像这样的开关语句从一个index.php文件提供多个页面:

switch(isset($_GET['q']{
    case 'page':
        require 'link_to_page.php';
        break;
    case 'login':
        require = 'link_to_login.php';
        break;
    default:
        require = 'link_to_404.php';
        break;
}

随着时间的推移,更多的页面被添加,我决定将其移动到一个selectPage()函数,我现在调用并分配给一个变量$page,并要求它在我的index.php文件,使事情变得更简单,像这样:

myFunctions.php
selectPage()
{
    switch(isset($_GET['q']{
        case 'page':
            $output = 'link_to_page.php';
            break;
        case 'login':
            $output = 'link_to_login.php';
            break;
        default:
            $output = 'link_to_404.php';
            break;
        return $output;
    }
}

我的index.php是这样的:

require 'myFunctions.php';
$page = selectPage();
require $page;

现在的问题是,无论哪种情况是true case page:case 'login':,返回的$output总是等于case条件检查的第一行,例如当case page:case语句的第一行和$_GET['q'] == 'login'时,返回的是case page: $output值,当我将case 'login':case page:交换为第一个检查条件时,返回的是case 'login': $output值,即现在是$_GET['q'] == 'page'条件的第一行。

我也试过用if(statement),同样的事情发生了。我怎么解决这个问题,有什么我做错了吗?

Switch语句语法错误。

右语法:

switch (n) {
    case label1:
        code to be executed if n=label1;
        break;
    case label2:
        code to be executed if n=label2;
        break;
    case label3:
        code to be executed if n=label3;
        break;
    ...
    default:
        code to be executed if n is different from all labels;
}

那么,myFunctions.php Page

function selectPage()
{
    $page = isset($_GET['q']) ? $_GET['q'] : null;
    switch ($page) {
        case "page":
            return 'link_to_page.php';
            break;
        case "login":
            return "link_to_login.php";
            break;
        default:
           return "link_to_404.php";
    }
}

index.php page

require 'myFunctions.php';
$page = selectPage();
require $page;

试试这个:

 switch($_GET['q']){
    ....
 }

您尝试检查$_GET['q'],但实际上您检查isset($_GET['q']),所以当PHP获得true时,它试图比较您在case语句中给出的值与true。如果您的值不为空或false值,则该条件为真,并且在此条件下的代码将执行。