How to alias a function in PHP?

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

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

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

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

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