【问题标题】:PHP | How do I access/modify a switch statement variable globally?PHP |如何全局访问/修改 switch 语句变量?
【发布时间】:2020-11-20 12:18:47
【问题描述】:

也许这个问题的措辞是错误的,但我在下面的 PHP switch 语句中遇到了一些问题。 我的目标是访问所有文件中的 $page 变量。我试图通过会话来做到这一点,但无法让它发挥作用。我的代码示例如下所示。这个问题可以用 $_GLOBALS$_SESSIONS 解决吗?请指出正确的方向。

Index.php

<?php
    
    /* Fetch needed files. */
    require_once 'app/paths.php';
    require_once THEME_LAYOUT_PATH . 'container.phtml';
    
    if(!isset($_GET['page']) || $_GET['page'] == ''){
        $page = 'home'; 
        } else {
        $page = $_GET['page'];
    }
    
    $layoutPath = 'themes/neutron/layout/' . $page . '/' . $page . '.phtml';
    
    switch($page) 
    {
        case 'home':
            include $layoutPath;
            break;
        case 'login':
            include $layoutPath;
            break;
        case 'register':
            include $layoutPath;
            break;
        default:
            include 'themes/neutron/layout/404/404.phtml';
    
    }
    
    ?>

Container.phtml

<html>
<?php if($page == 'login'){ ?> //Error: $page is undefined 
<link rel = "stylesheet" type = "text/css" href = "<?php ASSETS_PATH . 'css/file.css' ?>">
<?php } ?>


</html>

【问题讨论】:

  • require_once THEME_LAYOUT_PATH . 'container.phtml';$page = 之前也可以简化对$page = !empty($_GET['page']) ? $_GET['page'] : 'home'; 的赋值
  • 您似乎还缺少echo 这里&lt;?php ASSETS_PATH . 'css/file.css' ?&gt;
  • 我根本不明白你的 switch 语句的必要性
  • @GrumpyCrouton 好点,因为除了默认情况外,所有情况都做同样的事情。
  • 应该是 if (in_array($page, ["home", "login", "register"]))

标签: php html switch-statement global-variables undefined


【解决方案1】:

在设置 $page 变量之前,您需要 container.phtml。你的 switch 语句中包含的文件应该都可以访问全局 $page 变量,假设它们没有包装在类、函数或其他结构中。

编辑:这是您的代码在此更改后的样子:

<?php
    
    if(!isset($_GET['page']) || $_GET['page'] == ''){
        $page = 'home'; 
        } else {
        $page = $_GET['page'];
    }
    
    /* Fetch needed files. */
    require_once 'app/paths.php';
    require_once THEME_LAYOUT_PATH . 'container.phtml';
    
    $layoutPath = 'themes/neutron/layout/' . $page . '/' . $page . '.phtml';
    
    switch($page) 
    {
        case 'home':
            include $layoutPath;
            break;
        case 'login':
            include $layoutPath;
            break;
        case 'register':
            include $layoutPath;
            break;
        default:
            include 'themes/neutron/layout/404/404.phtml';
    
    }
    
    ?>

【讨论】:

  • 我没有投反对票。然而,虽然这个答案是正确的,但可以通过显示对代码的更正来改进它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
相关资源
最近更新 更多