Possible Duplicate:
autoload functions in php
I am working on a PHP framework. I wonder if there is a way to maybe rewrite the error handler when a function doesn't exist to automatically try to include the file stating the function first.
Example:
echo general_foo(); // <-- general_foo() is not yet stated.
// A handler tries to include_once('functions/general.php') based on the first word of the function name.
// If the function still doesn't exist - throw an error.
The win from this would be to skip compiling unnecessary files or to skip keeping track and state includes here and there.
Simply __autoload for functions rather than classes.
It does not exists and probably will never. Yes, I would like it too... However, this does not prevent you from using classes with static functions and let PHP autoload.
http://php.net/spl-autoload-register
I solved it like this
The class file classes/functions.php:
class functions {
public function __call($function, $arguments) {
if (!function_exists($function)) {
$function_file = 'path/to/functions/' . substr($function, 0, strpos($function, '_')).'.php';
include_once($function_file);
}
return call_user_func_array($function, $arguments);
}
}
The function file functions/test.php
function test_foo() {
return 'bar';
}
The script myscript.php:
require_once('classes/functions.php');
$functions = new functions();
echo $functions->test_foo(); // Checks if function test_foo() exists,
// includes the function file if not included,
// and returns bar
You could eventually autoload classes/functions.php by using __autoload().
In the end, the syntax for my_function() becomes instead $functions->my_function(). And you can write your own error handlers if functions doesn't exist. ;)