I've built a CMS for our company which has a huge number of functions, many of which are related to specific functionality which isn't used on most of the sites we use the CMS for. My goal, then, is to only include the script of a function when it's needed (when the function is called).
Right now I'm simply calling up each function as normal, requiring the file where the actual script of the function is located, and then calling a second function (the same name as the function, but with an underscore prefix) which contains the actual script of the function. For example:
function foo($a,$b) {
require_once "funtions-foo.php";
return _foo($a,$b);
}
This, however, seems a little repetitive to me. What I'm looking for is a way to either 'catch' a functions call and, if its name is in an array of 'included' functions, i'll include the correct file and call the function. For example:
catch_function_call($function,$arg1,$arg2) {
$array = array(
'foo' => 'functions-foo.php',
'bar' => 'functions-bar.php'
);
if($array[$function]) {
require_once $array[$function];
return $function($arg1,$arg2);
}
}
There I'm assuming the 'catch_function_call' function can somehow catch when a function is called. As I know of no such function, however, my second thought was to simply define each of the 'included' functions using variables. For example:
$array = array(
'foo' => 'functions-foo.php',
'bar' => 'functions-bar.php'
);
foreach($array as $function => $file) {
function $function($arg1,$arg2) {
$_function = "_".$function;
require_once $file;
return $_function($arg1,$arg2);
}
}
Of course, this gives me an error as I apparently can't use a variable in the name of a function when defining it. Any thoughts on how to get around this or other solutions for only including a function when it's needed?