php – 加载视图时CodeIgniter的意外行为

我有一个查看器帮助函数,可以在页脚/页眉旁边加载主要内容.当我为主内容视图中的变量共享相同名称的标头加载数组的键时,会发生错误/意外行为 – 为标题和主要内容加载相同的数组.

我认为这是正常的,因为同样的$data数组也被发送到标题和主要内容(如前所述).因此变量自然会出现在两个视图中.但是,嗯,这不完全是那样的.我将数据发送到标题后取消设置$data变量,然后在我想将一些数据发送到主视图时重新创建它 – 但问题仍然没有解决.

我为这个bug /意外行为做了一个简单的例子:

考虑这个名为test的视图:

<?PHP 
echo $some_data;

而这个控制器:

class Test extends CI_Controller {

    function index() {

    $data['some_data'] = 'Some data.';
    $this->load->view('test',$data);
    /* 
     * Output:
     * Some data.
     */
    unset($data);
    unset($data['some_data']);//Just to make sure it's not PHP's fault.
    $this->load->view('test');
    /*
     * Output:
     * Some data.
     * 
     * Even though the $data variable is unsetted AND not passed!
     */

    $different_data = array();

    $this->load->view('test',$different_data);     
    /*
     * Output:
     * Some Data.
     * 
     * Still outputs the same thing,even though
     * I'm sending different array(and the $data array is unstted).
     * 
     */ 

    }
}

注意:整个代码输出一些数据.三次.

解决此问题的唯一方法是发送一个不同的数组并将数组键(some_data)设置为覆盖旧数组的其他内容.

那么,这是CodeIgniter的家伙制造的bug还是其他东西?

解决方法

这是预期的行为.

一旦设置了变量,它们就会在控制器类及其视图文件中可用.在$this-> load-> view()中发送数组与在调用视图文件之前将数组直接发送到$this-> load-> vars()相同.这简化了大多数人在控制器中使用多个视图的过程.如果您在单个控制器中使用多个视图文件并希望它们各自拥有自己的一组变量,则需要在视图调用之间手动清除$this-> load-> _ci_cached_vars数组.

Loader类中的代码注释描述了另一种情况,显示了为什么这是所需的认行为:

//You can either set variables using the dedicated $this->load_vars()
//function or via the second parameter of this function. We'll merge
//the two types and cache them so that views that are embedded within
//other views can have access to these variables.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...