Welcome Guest, Not a member yet? Register   Sign In
scopes within a view
#1

[eluser]ggoforth[/eluser]
Hello All, just a quick question about the scope of functions within a view. I was having an issue accessing a config item in the main config file, when calling from a function within a view. So my code below does not work:


------ VIEW FILE -----

Code:
<?php

//this code fails

function echoConfigItem(){

$item = $this->config->item('some_array_key');
echo $item;

}

echoConfigItem();

?>

However, the code below does work:

------ VIEW FILE -----

Code:
<?php

define('SOME_GLOBAL_VAR',$this->config->item('some_array_key'));

function echoConfigItem(){

echo SOME_GLOBAL_VAR;

}

echoConfigItem();

?>

So, when I call the config item from outside the function in the view, everything works fine. I will say I solved the problem using the second method, I'm just curious about why I can't call the $this->config->item() function from within a function in a view.

Thanks all!

Greg
#2

[eluser]xwero[/eluser]
A function is a stand alone entity it has nothing to do with the view file. If you do
Code:
function echoConfigItem(){
$IC=& get_instance();
$item = $CI->config->item('some_array_key');
echo $item;

}
You will get the desired result.

As a side note it's better not to add functions to your view files. They should be display only.
#3

[eluser]ggoforth[/eluser]
[quote author="xwero" date="1220531280"]

As a side note it's better not to add functions to your view files. They should be display only.[/quote]

That is exactly what I was needed! Yeah, I agree with you about not having them in the views, but this is a legacy project, and I'm just fixing a few things, but not doing a rewrite of the program.

Thanks again!

Greg
#4

[eluser]Jamie Rumbelow[/eluser]
You might want to call global on the $this object, that should give you access to all of CI's functions from a view.

Code:
function echoConfigItem()
{
global $this;

echo $this->config->item("some_item");
}




Theme © iAndrew 2016 - Forum software by © MyBB