MD. AZMOL HOSSAIN
MD. AZMOL HOSSAIN

Reputation: 21

how to use custom helper in codeigniter

How to use custom helper in codeigniter? This function is not work inside of codeigniter but outside of codeigniter work properly

function next_element($array)
{

    static $index_position = 0;

    if ($index_position==count($array)) 
    {
        $index_position = 0; 
    }

    return $array[$index_position++];

}

$week = ['Saturday', 'Sunday','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' ];

echo next_element($week);   // return Saturday
echo next_element($week);   // return Sunday
echo next_element($week);   // return Monday

this helper function is not work inside of codeigniter

Upvotes: 1

Views: 878

Answers (1)

Javier Larroulet
Javier Larroulet

Reputation: 3237

I'm assuming you already have this function within a custom helper file in application/helpers, but just in case you don't, I'll walk you through it

First, create the helper file within the application/helpers directory. Name the file to you heart's desire, but suffix it with _helper (e.g., yourhelperfile_helper.php)

Second, add any and all helper functions you need in this way:

function someFunction()
{
  // your code goes here
}

function someOtherFunction()
{
  // other code goes here
}

Then, make sure your controller is actually loading the helper before you need to make use of it. You can do that in the controller's constructor if you think you'll need it on multiple methods within the controller. You could also autoload it so it's available across all of your controllers, or you could just load it in the specific places where you'll need to use some of those helper functions. In any case, load the helper with $this->load->helper('helpername'); without the _helper suffix. That is to say, if the helper file is called mysuperhelperfile_helper.php load it with $this->load->helper('mysuperhelperfile');

Finally, when you need to use a function/method from the helper, just use it like a regular function. In my example above, if the method you need is someFunction you can just use someFunction($params); within the controller or even within a view which is loaded by the controller.

Upvotes: 1

Related Questions