66

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 wait?

By now I'm doing like this:

function wait( $seconds ) {
    sleep($seconds);
}
Axel
  • 3,331
  • 11
  • 35
  • 58
Atif
  • 10,623
  • 20
  • 63
  • 96

16 Answers16

70

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());
}
Community
  • 1
  • 1
Lukman
  • 18,462
  • 6
  • 56
  • 66
  • 14
    `func_get_args()` will work like that only in PHP > 5.3 where you can use it in a parameter list. In PHP < 5.3 you have to use a temporary variable: `$args = func_get_args(); return call_user_unc_array('sleep', $args);` – Marko Nov 06 '09 at 18:57
  • This is my preferred answer because it also allows you to alias a static method inside of a class, like this: call_user_func_array(array("Class", "staticMethod"), func_get_args()); – OCDev Feb 20 '12 at 17:35
  • @FriendlyDev couldn't you just use `call_user_func_array("TheClass::theStaticMethod", func_get_args());` instead? – DiegoDD Aug 15 '14 at 21:18
  • Or if you want to be really fancy, `return sleep(...func_get_args());` – Brian Leishman Sep 21 '17 at 18:21
  • @AbiusX I had a function where the first variable was by reference, so this works for that `function v(&$v) { return Validate($v, ...array_slice(func_get_args(), 1)); }` – Brian Leishman Dec 18 '18 at 20:15
67

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").

Jon
  • 428,835
  • 81
  • 738
  • 806
  • 11
    How would this look for methods of a class? – Nathan J.B. Sep 27 '14 at 00:42
  • @NathanJ.Brauer: Are you asking how to call the method `foo` of an existing object using the name `bar`, calling a static method `foo` of a class using the name `bar`, or something else? For the two cases I mentioned, the short answer is you can't. – Jon Oct 10 '14 at 00:02
  • 5
    Here are all the ways (including the bad ways) that I know to alias a method of a class, both static and not: https://gist.github.com/nathanbrauer/cdd286351f68a1b4e3a5 – Nathan J.B. Oct 10 '14 at 07:15
  • @NathanJ.Brauer: All of that assumes that you own the class and are free to make modifications. But there is no language feature that allows you to do this "from the outside", as with `use (function) X as Y`. – Jon Oct 10 '14 at 15:19
  • 1
    Correct - I want to be able to, in my own class, provide useful aliases to those who use the class. Sometimes this is a means of graceful deprecation (e.g. a former version of a framework had a misspelled method), while other times it's just nice UX. – Nathan J.B. Oct 11 '14 at 02:27
  • 1
    It doesn't seem to work globally if used inside an included file in a procedural context. – Vincent Poirier Oct 20 '15 at 14:58
  • 4
    @VincentPoirier imports are per-file, it's not possible for another file to redefine a function for you. – Jon Oct 20 '15 at 15:06
  • You're correct! My nose was stuck to the "make it global" tree. I couldn't see the forest around it. – Vincent Poirier Oct 20 '15 at 15:13
30

Nope, but you can do this:

$wait = 'sleep';
$wait($seconds);

This way you also resolve arguments-number-issues

Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 2
    variable variables can get really confusing though. I don't think this is the best way to solve the problem here. – GSto Nov 06 '09 at 16:47
  • 5
    @GSto this wasn't meant to be the best solution. it was just a possibility. I can't believe it's been upvoted so much :-) – Federico klez Culloca Nov 06 '09 at 16:49
  • How much of another string contents are substituted in such way in PHP? Looks like an ```eval()``` integrated into each variable. Like mixed parser, preprocessor and interpreter into one very bad designed language. Note: I'm not a PHP programmer (C++, Python and Javascript). – Brian Cannard May 12 '15 at 15:00
  • 1
    These kinds of structures are the reason I started using PHP back in the day. Simple, human readable and anything is possible. Still loving it. – Oliver Manner Dec 05 '18 at 18:55
23

You can look at lambdas also if you have PHP 5.3

$wait = function($v) { return sleep($v); };
Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
9

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();
Nathan Crause
  • 874
  • 10
  • 7
6

No, there's no quick way to do this in PHP. The language does not offer the ability to alias functions without writing a wrapper function.

If you really really really needed this, you could write a PHP extension that would do this for you. However, to use the extension you'd need to compile your extension and configure PHP to us this extension, which means the portability of your application would be greatly reduced.

Alana Storm
  • 164,128
  • 91
  • 395
  • 599
5

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); }
Greg
  • 316,276
  • 54
  • 369
  • 333
5

you can use runkit extension

http://us.php.net/manual/en/function.runkit-function-copy.php

user187291
  • 53,363
  • 19
  • 95
  • 127
4
function alias($function)
{
    return function (/* *args */) use ($function){
        return call_user_func_array( $function, func_get_args() );
    };
}

$uppercase = alias('strtoupper');
$wait      = alias('sleep');

echo $uppercase('hello!'); // -> 'HELLO!'

$wait(1); // -> …
sam
  • 40,318
  • 2
  • 41
  • 37
3

If your PHP doesn't support use x as y syntax, in older PHP version you can define anonymous function:

$wait = create_function('$seconds', 'sleep($seconds);');
$wait(1);

Or place the code inside the constant, e.g.:

define('wait', 'sleep(1);');
eval(wait);

See also: What can I use instead of eval()?

This is especially useful if you've long piece of code, and you don't want to repeat it or the code is not useful for a new function either.


There is also function posted by Dave H which is very useful for creating an alias of a user function:

function create_function_alias($function_name, $alias_name) 
{ 
    if(function_exists($alias_name)) 
        return false; 
    $rf = new ReflectionFunction($function_name); 
    $fproto = $alias_name.'('; 
    $fcall = $function_name.'('; 
    $need_comma = false; 

    foreach($rf->getParameters() as $param) 
    { 
        if($need_comma) 
        { 
            $fproto .= ','; 
            $fcall .= ','; 
        } 

        $fproto .= '$'.$param->getName(); 
        $fcall .= '$'.$param->getName(); 

        if($param->isOptional() && $param->isDefaultValueAvailable()) 
        { 
            $val = $param->getDefaultValue(); 
            if(is_string($val)) 
                $val = "'$val'"; 
            $fproto .= ' = '.$val; 
        } 
        $need_comma = true; 
    } 
    $fproto .= ')'; 
    $fcall .= ')'; 

    $f = "function $fproto".PHP_EOL; 
    $f .= '{return '.$fcall.';}'; 

    eval($f); 
    return true; 
}
Community
  • 1
  • 1
kenorb
  • 155,785
  • 88
  • 678
  • 743
  • [`create_function()`](https://www.php.net/create-function) is deprecated as of PHP 7.2, and removed as of PHP 8.0. Using it is highly discouraged. – MAChitgarha Sep 04 '21 at 14:27
  • See also [When is `eval()` evil in PHP](https://stackoverflow.com/questions/951373/when-is-eval-evil-in-php). – MAChitgarha Sep 04 '21 at 14:28
1

nope. the way you wrote is the best way to do it.

GSto
  • 41,512
  • 37
  • 133
  • 184
1

No, there's no quick way to do so - at least for anything before PHP v5.3, and it's not a particularly good idea to do so either. It simply complicates matters.

Alister Bulman
  • 34,482
  • 9
  • 71
  • 110
1

Since PHP 5.6

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 ..."

Community
  • 1
  • 1
Nathan J.B.
  • 10,215
  • 3
  • 33
  • 41
0

Another way to do it:

Using ... to access variable arguments

<?php

function wait(...$args) {
  // Unpack the arguments
  sleep(...$args);
}

?>

This way you can call the alias just like the way you call the original function. Incase the function accept more than one argument.

-1

I know this is old, but you can always

$wait = 'sleep';
$wait();
Petruza
  • 11,744
  • 25
  • 84
  • 136
  • 2
    Isn't this equivalent to [this existing answer](http://stackoverflow.com/questions/1688711/can-we-alias-a-function-in-php/1688787#1688787)? – Pang May 06 '16 at 05:03
  • @Pang Yes, but my memory isn't that good as to answer why did I do that months ago. – Petruza May 08 '16 at 02:05
-2

What I have used in my CLASS

function __call($name, $args) {
    $alias['execute']=array('done','finish');
    $alias['query']=array('prepare','do');
    if (in_array($name,$alias['execute'])){
        call_user_func_array("execute",$args);
        return TRUE;
    }elseif(in_array($name,$alias['query'])){
        call_user_func_array("query",$args);
        return TRUE;
    }
    die($this->_errors.' Invalid method:'.$name.PHP_EOL);
}
Abbas
  • 552
  • 5
  • 8