James Dawson
James Dawson

Reputation: 5409

Restricting variable use to one file

Bit of a weird question but bear with me. I'm writing a small MVC framework mostly for learning purposes. When I load views, I just include the view file and then use extract($data); so I can use variables in my view. This is that it looks like in my controller:

// Assign view variables and load the views
$data = array('title' => 'testing the framework',
              'users' => $this->models['Users']->getAllUsers());
$this->loadViews(array('header', 'home', 'footer'), $data);

It works perfectly, but it just occured to me that if I have any variables elsewhere in my project that are called $title or $users, they will conflict to what I'm extract()'ing. THis hasn't become a problem yet but I have a feeling I need to deal with it now before it does.

The only solution I've found is using a prefix for the variables being extract()ed. SO I can use them in my template like <?php echo $tpl_whatever; ?> instead of <?php echo $whatever; ?>

Can anyone offer some advice? Maybe a way I can limit the variables scope?

Thanks!

Upvotes: 1

Views: 90

Answers (2)

Baba
Baba

Reputation: 95101

Only variables in your method can have conflict See Variable Scope but if such happens you can resolved conflict in extract easy with extra flags such as EXTR_PREFIX_ALL.

You can also look at EXTR_PREFIX_SAME , EXTR_SKIP or EXTR_OVERWRITE to resolve possible collusion during extraction

Your Variables

$name = "Baba";
$array = array("title" => "Restricting variable use to one file",
               "name"  => "James Dawson");

Example EXTR_PREFIX_ALL

extract($array,EXTR_PREFIX_ALL,"new");
var_dump($new_title,$new_name,$name);
           ^------------------------------ it now has prifix

Output

string 'Restricting variable use to one file' (length=36)
string 'James Dawson' (length=12)
string 'Baba' (length=4)


Example EXTR_PREFIX_SAME

extract($array, EXTR_PREFIX_SAME, "prifix");
var_dump($name,$title,$prifix_name);
                           ^------------------ Only Conflict has prifix

Output

string 'Baba' (length=4)
string 'Restricting variable use to one file' (length=36)
string 'James Dawson' (length=12)

Upvotes: 3

Johndave Decano
Johndave Decano

Reputation: 2113

There will no conflict with other controller because the $data variables that you are extracting are private. Also if your variable has duplicate inside your controllers function, the last declaration will be the one to be used.

Upvotes: 0

Related Questions