Claudio Ɯǝıs Mulas
Claudio Ɯǝıs Mulas

Reputation: 1113

Codeigniter vars inside a view functions

I've a function inside a view (I've nested code so there is no alternative). My problem is made because i want to add some vars inside the function.

I can't access to the var inside the function.

<div>
<?php _list($data); ?>
</div>

<?php
echo $pre; // Perfect, it works
function _list($data) {
     global $pre;
     foreach ($data as $row) {
          echo $pre." ".$row['title']; // output ' title' without $pre var
          if (isset($row['childrens']) && is_array($row['childrens'])) _list($row['childrens']);
     }
}
?>

Upvotes: 0

Views: 43

Answers (2)

ied3vil
ied3vil

Reputation: 939

Simple... just define the function like this:

function _list($data, $pre=NULL)

then inside the function, you could check if the $pre is NULL then search for it somewhere else... using the global statement in functions is not desirable.

On the other hand you can define('pre',$pre); and use the pre constant created in your function... again not desirable but it would work for your example.

Later edit: DEFINE YOUR FUNCTIONS IN HELPERS i am not sure why i forgot to suggest that in the first place

Upvotes: 1

尤川豪
尤川豪

Reputation: 479

define function in view is weird. using global variable make it worse.

maybe you should avoid the global function with this:

<div>
<?php
    foreach($data as $row){
        _list($pre, $row);
    }
?>
</div>

<?php
function _list($pre, $row) {
    echo $pre." ".$row['title'];
    if (isset($row['childrens']) && is_array($row['childrens'])){
        foreach($row['childrens'] as $child){
            _list($pre, $child);
        }
    }
}
?>

btw, define function in helpers would be better

http://ellislab.com/codeigniter/user-guide/general/helpers.html

whsh they help

Upvotes: 0

Related Questions