Atif
Atif

Reputation: 10880

How to alias a function in PHP?

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);
}

Upvotes: 68

Views: 55623

Answers (16)

SYSA
SYSA

Reputation: 3

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.

Upvotes: 0

Jon
Jon

Reputation: 437336

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

Upvotes: 67

Nathan J.B.
Nathan J.B.

Reputation: 10315

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

Upvotes: 1

Petruza
Petruza

Reputation: 12276

I know this is old, but you can always

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

Upvotes: -1

Lukman
Lukman

Reputation: 19164

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());
}

Upvotes: 72

kenorb
kenorb

Reputation: 166359

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; 
}

Upvotes: 3

Abbas
Abbas

Reputation: 560

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);
}

Upvotes: -2

sam
sam

Reputation: 40668

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); // -> …

Upvotes: 4

Nathan Crause
Nathan Crause

Reputation: 943

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();

Upvotes: 9

Alana Storm
Alana Storm

Reputation: 166066

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.

Upvotes: 6

Alister Bulman
Alister Bulman

Reputation: 35139

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.

Upvotes: 1

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

Nope, but you can do this:

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

This way you also resolve arguments-number-issues

Upvotes: 31

user187291
user187291

Reputation: 53940

you can use runkit extension

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

Upvotes: 5

&#211;lafur Waage
&#211;lafur Waage

Reputation: 69991

You can look at lambdas also if you have PHP 5.3

$wait = function($v) { return sleep($v); };

Upvotes: 23

Greg
Greg

Reputation: 321598

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); }

Upvotes: 5

GSto
GSto

Reputation: 42350

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

Upvotes: 1

Related Questions