【问题标题】:Acquiring a global variable in a helper function with CodeIgniter使用 CodeIgniter 在辅助函数中获取全局变量
【发布时间】:2011-11-03 00:45:05
【问题描述】:

我正在制作一个函数,它将在我的视图中插入一些简单的 HTML。我已经做了好几次没有问题了,但是这次我将使用在Controller中设置的变量->提取到视图中。

现在,我显然不想放弃我的单行快捷方式:<?php echo showStatusMessages(); ?>,通过检查变量是否已设置,然后将它们作为参数等发送,因为这完全扼杀了函数调用的意义。

经过一番尝试和失败,我最终得到了一个我想在我的函数中使用的受保护属性。知道如何解决这个问题吗?

// Outputs success/error messages
function showStatusMessages() {

    $variables = array(
        'success',
        'error'
    );

    foreach ($variables as $variable) {
        // Cannot access protected property CI_Loader::$_ci_cached_vars
        if ($variable = $GLOBALS['CI']->load->_ci_cached_vars[$variable]) ${$variable} = $variable;
        break;
    }

    ob_start();

    // Success message set
    if (isset($success)) :
        echo '<div class="message_box success_color">'.$success.'</div>';
    endif;

    // Error message set
    if (isset($error)) :
        echo '<div class="message_box error_color">'.$error.'</div>';
    endif;

    $msg = ob_get_contents();
    ob_end_clean();

    return $msg;

}

【问题讨论】:

    标签: php codeigniter scope global-variables


    【解决方案1】:

    您不使用视图是否有原因?

    <?php if (isset($success)) : ?>
        <div class="message_box success_color"><?php echo $success; ?></div>
    <?php endif; ?>
    <?php if (isset($error)) : ?>
        <div class="message_box error_color"><?php echo $error; ?></div>
    <?php endif; ?>
    

    然后使用单线调用此视图,如下所示(假设您将视图命名为“statusMessage”:

    <?php $this->load->view('statusMessage'); ?>
    

    以这种方式完成您的功能正在尝试做的事情;您可以在一行中多次调用它。

    【讨论】:

    • 奇怪的是我没有想到那种优雅而简单的解决方案。回到过去,我只会使用简单的include() 语句,有趣的是,使用框架会使这种简单化的思维复杂化。谢谢!
    【解决方案2】:

    同意这不是首选方法,但是分配$GLOBAL 可以正常工作,并且可以在层次结构中运行的函数下方访问。尝试将其分配给$GLOBALS['ci'] 时会遇到麻烦。

    在您的助手中:

    function saveSomething($id){
        $GLOBAL['savedVars'][] = $id;
    }
    

    在您的助手被调用后,您认为:

    var_dump($GLOBAL['savedVars']);
    

    【讨论】:

      猜你喜欢
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 2014-01-23
      • 2023-03-25
      • 2016-03-14
      • 1970-01-01
      相关资源
      最近更新 更多