Welcome Guest, Not a member yet? Register   Sign In
Im sure you can solve this but...
#1

[eluser]Tom Taila[/eluser]
Hey Im kinda new to php and code igniter, ive got quite a good understanding so far but i just want to clarify how to access variables in my view, i mean lets say i have a variable in a controller which i want to be displayed in my view how do i do that, do i need to using the 'return' key word or something? coz sometimes i get it working but other times i get the undeclared variable error, i feel as though this may be the last piece in the puzzle for me to really get the ball rolling
#2

[eluser]bretticus[/eluser]
From the manual for $this->load->view() ...

Quote:The second optional parameter can take an associative array or an object as input, which it runs through the PHP extract function to convert to variables that can be used in your view files. Again, read the Views page to learn how this might be useful.

This means that you should have an associative array element for every standalone variable in your view.

So if you have a controller called Foo and it has a function (method because its a class) called bar, you might have code that looks like this:

Code:
class Foo extends Controller {

function bar()
{
//let's initialize an empty array called $data
$data = array();
//let's set a variable as an associative array element that we can get from our view.
$data['myvar'] = 'hello world';
$this->load->view('myview', $data); // the $data array to the view file.
}
}

Inside of my myview.php view file, I can echo out $myvar:

Code:
<html>
<body>
<h1>Title</h1>
<p>&lt;?=$myvar?&gt;</p>

Now here's the trick. You must add an array element with a corresponding associative array key for each variable you use in your view. So, to avoid the undeclared variable warning, you must have declared
Code:
$data['myvar'] = 'anything'
before passing $data to the view and trying to use $myvar in your view.
#3

[eluser]Tom Taila[/eluser]
wow thankyou so much, makes perfect sense, such a detailed response which im sure will work and will be using tomorrow when i wake up as its 5 am now lol (i've been working hard), ill let you know how it goes then, thanks so much aggain and goodnight




Theme © iAndrew 2016 - Forum software by © MyBB