CodeIgniter Forums
CodeIgniter helper functions - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: CodeIgniter helper functions (/showthread.php?tid=91927)



CodeIgniter helper functions - Dilemma - 11-10-2024

In CodeIgniter helper functions, I've seen that they check if they're being declared already before declaring like this:



Code:
if(!function_exists('foo'))
{
  function foo()
  {....
  }
}


Why is this necessary? I feel it's less readable and not good for code maintenance in the long run. Is there any workaround to this? For example, can I ensure in some other way that my helper.php will be loaded only once and not multiple times?


RE: CodeIgniter helper functions - allone - 11-17-2024

It's to avoid fatal errors due to redeclaration of functions. If you have a function called 'foo' declared somewhere else, when trying to redeclare it, the script will produce a fatal error. By implementing this check, if the function is already declared, the script will continue, but you won't see the new function at work, since it will not be declared.
I would also add:

```
} else {
log_message('error', 'The \'foo\' function was declared previously');
}
```