How to alias a function in PHP?

前端 未结 15 1202
死守一世寂寞
死守一世寂寞 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 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();
    

提交回复
热议问题