Is it possible to alias a function with a different name in PHP? Suppose we have a function with the name sleep
. Is there a way to make an alias called wa
Nope, but you can do this:
$wait = 'sleep';
$wait($seconds);
This way you also resolve arguments-number-issues
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").
No, functions aren't 1st-class citizens so there's no wait = sleep
like Javascript for example. You basically have to do what you put in your question:
function wait ($seconds) { sleep($seconds); }
you can use runkit extension
http://us.php.net/manual/en/function.runkit-function-copy.php
This is especially helpful for use in classes with magic methods.
class User extends SomethingWithMagicMethods {
public function Listings(...$args) {
return $this->Children(...$args);
}
}
But I'm pretty sure it works with regular functions too.
function UserListings(...$args) {
return UserChildren(...$args);
}
Source: PHP: New features -> "Variadic functions via ..."
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();