Welcome Guest, Not a member yet? Register   Sign In
Can't send data from controller to view - variable scope problem?
#9

[eluser]CroNiX[/eluser]
[quote author="duartix" date="1377855224"]

From what I've gathered about PHP, the scope of $data is local to the Home controller class, so it would make sense that the view wouldn't see it, but then again I'm passing it explicitly... If I change $data to $GLOBALS it will work, but it looks very dirty from an abstraction point of view.

So why does it work on the tutorial? Are the tutorial's view and controller married in a way that I am missing and share their little dirty data? How else can I send that data?
[/quote]
When you pass an array to a CI View, CI takes that array variable and runs it through php's extract(), which makes that arrays keys available as individual variables within the view.

Try this:
Code:
$test = array(
  'one' => 'first',
  'two' => 'second',
  'three' => array('a', ' separate', ' array')
);

extract($test);

echo $one; // outputs 'first'
echo $two; // outputs 'second'
echo $three; //oops, error, this is an array...

//iterate over it
foreach($three as $value)
{
  echo $value;
}
//echo's 'a separate array'

I think the only thing you were doing wrong in the initial post was accessing the variable in the view.
Code:
Connected as:
        <?php echo $data['connection']['username'] ?>
should have been
Code:
Connected as:
        <php echo $connection['username'] ?&gt;


Messages In This Thread
Can't send data from controller to view - variable scope problem? - by El Forum - 08-30-2013, 02:54 PM



Theme © iAndrew 2016 - Forum software by © MyBB