In my view I test if (isset($winner))
. However, the view is reprinted in a loop and I cannot clear it for subsequent tests.
How can I instantiate a new View or clear/unset the variables given by it's controller?
I appreciate the Views have a broad scope, but this seems like a bug in Codeigniter.
Controller:
for($i=0; $i < 100; $i++) {
$test = $this->prizedistributor->isWinner();
echo $this->load->view("simulateResponse", $test, TRUE);
unset($test['winner']); // this does not work
}
View:
<? if (isset($winner)):?>
WINNER!
<? else: ?>
LOST!
<? endif; ?>
<?php unset($winner); // this does not work! ?>
The Results:
Say $i==40
is the only winner, the View will report ALL $i's > 40 as winners despite the Controller always defaulting the Boolean as false.
UPDATE
I am aware testing if(empty($test)) allows the View to report correctly. However, my question is how to unset that variable (and clear it from memory). This question largely stems from other similar issues while using HMVC (modular codeigniter). However posting that code here would be too complicated to illustrate the same issue of scope.
Many folks keep questioning irrelevant prizedistributor above. So here is a simpler code sample to illustrate the sampe problem:
CONTROLLER
function testScope() {
for($i=0; $i < 10; $i++) {
if($i == 5)$winner = array('winner' => true);
else $winner = array();
echo $this->load->view("testScope", $winner, TRUE);
}
}
VIEW
<?= (isset($winner)) ? "WINNER!<br>" : "LOST!<br>"; ?>
OUTPUT
LOST! LOST! LOST! LOST! LOST! WINNER! WINNER! WINNER! WINNER! WINNER!
Possible Answer:
I've looked into codeigniter's system/core/Loader.php
and find function _ci_load
caches variables around line 800. They're reasoning being:
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.
This brings up a very good point and something I appreciate about codeigniter. But the question remains, how can we have both? Possibly a 4th optional parameter to skip this catching?
ex. loader->view("testScope", $winner, TRUE, FALSE);
????