Search code examples
phpcodeignitercodeigniter-2

Unset the variables of a view for sub-views in codeigniter


Controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller 
{

    public function index()
    {
        $this->load->model('Event');
        $todays_events = $this->Event->get_todays_events();     

        $data = array(
            'todays_events' => $todays_events
        );
        $this->load->view('main/index', $data);
    }
}
?>

main/index view

<?php $this->load->view('partial/header'); ?>
<?php $this->load->view('components/calendar/mon_to_wed'); ?>
<?php $this->load->view('partial/footer'); ?>

components/calendar/mon_to_wed

(Has access to $todays_events, why is this?)

<div id="calendar_today">
    <h1>Whats Happening</h1>
    <?php foreach($todays_events as $event) : ?>
        <?php var_dump($event); ?>
    <?php endforeach; ?>
</div>

Solution

  • I've read the CodeIgniter core files, while hacking the core may solve this issue, another method exists that help to prevent defining variables in inner-views.

    In the first view file, do this instruction:

    foreach ($_ci_vars as $key => $value) $_ci_vars[$key]=NULL;
    
    $this->load->view('your-inner-view', $_ci_vars);
    $this->load->view('your-second-inner-view', $_ci_vars);
    $this->load->view('your-third-inner-view', $_ci_vars);
    // and so on...
    

    I'll update my post, if I find a better solution

    UPDATE:

    Finally! I found the real solution, it is better to make your own Loader class instead of using default one. do the instructions below:

    • Copy Loader.php class from /system/core/ to your /application/core/
    • Find $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); at line #805
    • change/replace that line to $this->_ci_cached_vars = $_ci_vars;

    CodeIgniter has a variable cashing, once you use load->view() method, the variables will be cached in an array, and the second using of load->view() caused to merge cached variables and new variables if exists and then cache the result as a new array (which contains the old variables).

    So, stop using of array_merge() would be the solution ;)