微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP-将变量从MY_Controller传递到视图

在我的网站上,我有一个登录提示”,该提示在每个页面上都可见.我使用的是模板系统,因此此登录提示出现在每个页面标题中.

用户登录后,应显示用户名和注销链接.未登录时,将显示登录注册链接.

我在MY_Controller中有一个函数,该函数检查用户是否在每次页面加载时均已登录,效果很好:

if($this->is_logged_in()) {
    $this->username = $this->session->userdata('username');
    $data['login_prompt'] = "Hi, " . $this->username . " " . anchor("account/logout", "logout");
}

在我的header.PHP(视图)中,我有

<div id="login-prompt" class="transparent">
    <?PHP
        if (!isset($login_prompt)) $login_prompt = anchor("account/login", "Login") . " or " . anchor("account/register", "register");
        echo $login_prompt;
    ?>
</div>

问题出在我的控制器上.这是ucp.PHP的构造函数,它扩展了MY_Controller:

public $data;

function __construct()
{
    parent::__construct();
    $data['login_prompt'] = $this->data['login_prompt'];
}   

我希望$data [‘login_prompt’]在控制器的每个方法中都可用,以便可以将其传递到视图.但是,打印$data [‘login_prompt’]会给出“未定义的索引”错误,结果,header.PHP中定义的认“登录注册”消息始终可见.

ucp.PHP中的典型方法如下:

function index()
{
    $this->template->build("ucp/ucp_view", $data);
}

如您所见,应该将$data数组传递给视图.如果我要在方法本身而不是构造函数中定义$data [‘login_prompt’],则:

function index()
{
    $data['login_prompt'] = $this->data['login_prompt'];
    $this->template->build("ucp/ucp_view", $data);
}

登录提示更改为正确的已登录消息.但是,我不想将此行添加到应用程序中每个控制器的每个方法中.

我发现的一个类似问题涉及简单地将传递给视图的$data数组更改为概述为here的$this-> data.此方法有效,但破坏了应用程序的其他部分.

我觉得错误很明显.我究竟做错了什么?

解决方法:

您有几种选择

您可以在MY_Controller上使用$this-> data属性,然后确保将$this-> data传递给所有视图

// MY_Controller
public $data;

public function __construct()
{
    if($this->is_logged_in()) 
    {
        $this->username = $this->session->userdata('username');
        $this->data['login_prompt'] = "Hi, " . $this->username . " " . anchor("account/logout", "logout");
    }
}

然后在我们的控制器中.

// An example controller. By extending MY_Controller 
// We have the data property available
UcpController extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->data['Some extra variable'] = 'Foo';
        // Notice we are giving $this->data rather than $data...
        // this means we will have our login prompt included
        // as it is set by the parent class
        $this->template->build("ucp/ucp_view", $this->data);
    }
}

或者,您可以在MY_Controller中设置全局数组,然后使用load-> vars方法使该数组可用于所有视图

// MY_Controller
public $global_data;

public function __construct()
{
    if($this->is_logged_in()) 
    {
        $this->username = $this->session->userdata('username');
        $this->global_data['login_prompt'] = "Hi, " . $this->username . " " . anchor("account/logout", "logout");

        $this->load->vars($this->global_data);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐