Welcome Guest, Not a member yet? Register   Sign In
Functions inside views, access to "this" or other vars
#1

[eluser]pmhart[/eluser]
I am writing a view that prints out the exact same thing in two different areas, so I wrote a function that prints it out in the view.

However, the function doesn't seem to have access to the "is_logged_in" variable passed to the view:

$data["is_logged_in"] = true;
$this->load->view("view_name", $data);

I tried using "global", I tried passing $this to the function.

There are a lot more than just the $is_logged_in variable, otherwise I would pass it as a param and not worry about accessing it directly from the code.

Can anyone help me figure out how I can access these $data vars?
#2

[eluser]skunkbad[/eluser]
Maybe something like this would work for you?

Code:
<?php
function whatever($is_logged_in)
{
     echo (isset($is_logged_in))? $is_logged_in : '' ;
}
whatever($is_logged_in);
echo '<br />';
whatever($is_logged_in);
#3

[eluser]Colin Williams[/eluser]
Show snippets of your view code and we'll have a better idea of the problem.
#4

[eluser]nubianxp[/eluser]
How about defining
Code:
$this->load->vars($var)
from you constructor function?

Code:
function __constructor() {
  $var = array {
    'is_logged_in' => 'true',
  };
  $this->load->vars($var);
}

I'm a noob myself, but I think this would make the variable available on all the functions inside the controller.

HTH
#5

[eluser]bigtony[/eluser]
I would approach it a bit differently. Presumably you derive if someone is logged in by using a session variable, so instead of passing the flag into the view, you can do either of the following:

Method 1 - using just the view:
Code:
&lt;?php if ($this->session->userdata('is_logged_in') == TRUE: ?&gt;
    <p>You are logged in</p>
&lt;?php else: ?&gt;
    <p>You are NOT logged in</p>
&lt;?php endif: ?&gt;


Method 2 - using a function and a view:
Code:
// This is in a helper
function logged_in_output() {
    $CI =& get_instance();
    if ($CI->session->userdata('is_logged_in') == TRUE):
      return 'You are logged in';
    else:
      return 'You are NOT logged in';
    endif;
}
Code:
&lt;!-- This is in your view --&gt;
&lt;?php echo logged_in_output(); ?&gt;

Choose whichever seems more useful (method 2 is better if you need to reuse in many places).


It's best to avoid global variables or trying to define functions in views if at all possible.
#6

[eluser]pmhart[/eluser]
thanks bigtony, that's what I was looking for!




Theme © iAndrew 2016 - Forum software by © MyBB