How to alias a function in PHP?

前端 未结 15 1060
死守一世寂寞
死守一世寂寞 2020-11-30 00:13

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

相关标签:
15条回答
  • 2020-11-30 00:57

    Nope, but you can do this:

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

    This way you also resolve arguments-number-issues

    0 讨论(0)
  • 2020-11-30 01:02

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

    0 讨论(0)
  • 2020-11-30 01:03

    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); }
    
    0 讨论(0)
  • 2020-11-30 01:03

    you can use runkit extension

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

    0 讨论(0)
  • 2020-11-30 01:03

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

    0 讨论(0)
  • 2020-11-30 01:04

    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();
    
    0 讨论(0)
提交回复
热议问题