How to alias a function in PHP?
Solution 1:
Until PHP 5.5
yup, function wait ($seconds) { sleep($seconds); }
is the way to go. But if you are worried about having to change wait() should you change the number of parameters for sleep() then you might want to do the following instead:
function wait() {
return call_user_func_array("sleep", func_get_args());
}
Solution 2:
PHP 5.6+ only
Starting with PHP 5.6 it is possible to alias a function by importing it:
use function sleep as wait;
There's also an example in the documentation (see "aliasing a function").
Solution 3:
Nope, but you can do this:
$wait = 'sleep';
$wait($seconds);
This way you also resolve arguments-number-issues
Solution 4:
You can look at lambdas also if you have PHP 5.3
$wait = function($v) { return sleep($v); };
Solution 5:
If you aren't concerned with using PHP's "eval" instruction (which a lot of folks have a real problem with, but I do not), then you can use something like this:
function func_alias($target, $original) {
eval("function $target() { \$args = func_get_args(); return call_user_func_array('$original', \$args); }");
}
I used it in some simple tests, and it seemed to work fairly well. Here is an example:
function hello($recipient) {
echo "Hello, $recipient\n";
}
function helloMars() {
hello('Mars');
}
func_alias('greeting', 'hello');
func_alias('greetingMars', 'helloMars');
greeting('World');
greetingMars();