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?

wnrph
  • 3,293
  • 4
  • 26
  • 38

2 Answers2

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.

Luke Dennis
  • 14,212
  • 17
  • 56
  • 69
  • Thanks for the details. The fact include files use that function's scope by which they are included was the hint I needed. – wnrph Apr 20 '12 at 17:49
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?

Community
  • 1
  • 1
lracicot
  • 364
  • 2
  • 15