How to alias a function in PHP?

前端 未结 15 1059
死守一世寂寞
死守一世寂寞 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:46

    You can look at lambdas also if you have PHP 5.3

    $wait = function($v) { return sleep($v); };
    
    0 讨论(0)
  • 2020-11-30 00:49

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

    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.

    0 讨论(0)
  • 2020-11-30 00:52
    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); // -> …
    
    0 讨论(0)
  • 2020-11-30 00:52

    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.

    0 讨论(0)
  • 2020-11-30 00:56

    I know this is old, but you can always

    $wait = 'sleep';
    $wait();
    
    0 讨论(0)
提交回复
热议问题