How to alias a function in PHP?

PhpFunctionAlias

Php Problem Overview


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

Php Solutions


Solution 1 - Php

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

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 - Php

Nope, but you can do this:

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

This way you also resolve arguments-number-issues

Solution 4 - Php

You can look at lambdas also if you have PHP 5.3

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

Solution 5 - Php

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

Solution 6 - Php

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 http://talks.php.net/show/extending-php-apachecon2003/0">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.

Solution 7 - Php

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

Solution 8 - Php

Solution 9 - Php

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

Solution 10 - Php

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

Solution 11 - Php

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

Solution 12 - Php

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.

Solution 13 - Php

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

Solution 14 - Php

I know this is old, but you can always

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

Solution 15 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAtifView Question on Stackoverflow
Solution 1 - PhpLukmanView Answer on Stackoverflow
Solution 2 - PhpJonView Answer on Stackoverflow
Solution 3 - PhpFederico klez CullocaView Answer on Stackoverflow
Solution 4 - PhpÓlafur WaageView Answer on Stackoverflow
Solution 5 - PhpNathan CrauseView Answer on Stackoverflow
Solution 6 - PhpAlan StormView Answer on Stackoverflow
Solution 7 - PhpGregView Answer on Stackoverflow
Solution 8 - Phpuser187291View Answer on Stackoverflow
Solution 9 - PhpsamView Answer on Stackoverflow
Solution 10 - PhpkenorbView Answer on Stackoverflow
Solution 11 - PhpGStoView Answer on Stackoverflow
Solution 12 - PhpAlister BulmanView Answer on Stackoverflow
Solution 13 - PhpNathan J.B.View Answer on Stackoverflow
Solution 14 - PhpPetruzaView Answer on Stackoverflow
Solution 15 - PhpAbbasView Answer on Stackoverflow