We occasionally need some common global functions during our development. In core PHP, we can create a file, say functions.php (don’t confuse it with wordpress functions.php). We can include this file in any other file to access its functions. But, CodeIgniter is a MVC framework and it follows Object-oriented programming. Everything is managed in it in proper way.
To declare a global function in CodeIgniter, you need to create a helper file in “application/helpers/
” directory. Let’s name this file as “site_helper.php
“.
Now, place your functions inside this file. Don’t forget to check if function already exists or not otherwise, you might get “function already declared” error.
if(!function_exists('remove_comma')) {
function remove_comma($value) {
return str_replace(',','',$value);
}
}
Then, after creating the file, you can manually load this file in the controller class. Or, you can auto-load it everywhere, by default.
Auto-load by default:
Open “config/autoload.php
” and update the $autoload['helpers']
variable.
$autoload['helpers'] = array('site');
Remember, you don’t have to specify “_helper.php” because CI automatically checks for it.
Manual Loading:
To load helper file in a specific controller, put the following line of code in Controller constructor function.
$this->load->helper('site');
That’s all, now you can call the function directly from controller or view just like as follows.
remove_comma('This comma, will be removed');