How to access View's local variable in the View's function

I am passing a variable from the controller in the view by the render method:

Inside Controller Action:

$this->render('add', array('value'=> $value);

Inside the ‘Add’ View file, there is a function, which needs to access the above variable $value:

function useValue()


   $value = //some calculation;


How to access the variable $value in this function of the view file? I have tried with the keyword ‘global’ in the view file, but does not solve the problem…

You would need to pass the value to the function like you would do otherwise:

function useValue($value)


    $value = //some calculation;

    return $value;


// In view file:

$value = useValue($value);

It’s worth considering whether you really want to use a function in a view though. You should typically try to keep view files as clean as possible and do all the calculations in either a controller method or a model method.

Thanks for the reply…

This is how i am doing it. I was thinking there would be some other way, which i did not know…

As you suggest, maybe i should move it to the controller, bcoz the calculation is little complex and in the actual implementation the function is recursive.

Keep controllers as simple as possible, make your models do the calculations that they should take care of the operations related to the models.

There is nothing wrong with putting functions in views if they are strictly specific to that view. I normally try and keep the functions anonymous to stop the namespace from being polluted. I’ve actually only put a few functions in a view and that was only when I needed recursion.

Thank you, Luke, for the support.

Because after my earlier reply, i was actually thinking that the controller or the model may not be the better place for the function, and it should be left in the view itself…