2

In codeigniter templates are basically include files and template input is made available by associative arrays. I guess codeigniter uses extract() for that part of the magic, but how does it prevent those variables to mess up the global scope? Or am I missing something with variable scope in include files?

1
  • 2
    They're simply in a method's scope (view() for example) Commented Apr 20, 2012 at 10:23

2 Answers 2

1

It does indeed use extract(). While the extract function has an option not to overwrite existing variables, by default it does overwrite, and CodeIgniter uses this default.

Since the view is ostensibly the final endpoint of your application, and should not use any variables except what you pass through the view, it is intended that this should not present any issues. However, if you wish to catch scope collisions, you can do something like this:

$foo = 'bar';
$data = array('foo' => 'baz');

foreach($data as $key => $val)
    if(isset($$key)) { /* throw fatal error */ }

$this->load->view($data);

To answer your question in a more technical and less practical way, the commenter above is correct: variables resolve within the method scope of the _ci_load function, inside the CI_loader class.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the details. The fact include files use that function's scope by which they are included was the hint I needed.
0

There is no conflicts with the global scope because the views are loaded within a method.

CodeIgniter is using extract(): https://github.com/EllisLab/CodeIgniter/blob/develop/system/core/Loader.php#L886

CodeIgniter's code to include a view: https://github.com/EllisLab/CodeIgniter/blob/develop/system/core/Loader.php#L910

Include within a method causes no conflicts with the global scope: How to use include within a function?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.