skip to Main Content
function _detect_argv(){
    if(_cmd()){
        $arg1=isset($_SERVER['argv'][1])?$_SERVER['argv'][1]:'';
        $arg2=isset($_SERVER['argv'][2])?$_SERVER['argv'][3]:'';
        $arg3=isset($_SERVER['argv'][3])?$_SERVER['argv'][3]:'';
        $arg4=isset($_SERVER['argv'][4])?$_SERVER['argv'][4]:'';
        $arg5=isset($_SERVER['argv'][5])?$_SERVER['argv'][5]:'';
        if(!empty($arg1)&&!empty($arg2)&&!empty($arg3)&&!empty($arg4)&&!empty($arg5)){
            $arg1($arg2,$arg3,$arg4,$arg5);
        }elseif(!empty($arg1)&&!empty($arg2)&&!empty($arg3)&&!empty($arg4)){
            $arg1($arg2,$arg3,$arg4);
        }elseif(!empty($arg1)&&!empty($arg2)&&!empty($arg3)){
            $arg1($arg2,$arg3);
        }elseif(!empty($arg1)&&!empty($arg2)){
            $arg1($arg2);
        }elseif(!empty($arg1)){
            $arg1();
        }
        system('exit');die;
    }
}

There are a lot of arguments, it looks like this code is not clean, how to simplify this function?

2

Answers


  1. Try this :

    function _detect_argv() {
        if (_cmd()) {
            $args = $_SERVER['argv'];
            array_shift($args);
    
            if (!empty($args)) {
                $functionName = array_shift($args);
                if (function_exists($functionName)) {
                    call_user_func_array($functionName, $args);
                } else {
                    echo "Function {$functionName} does not exist.n";
                }
            }
    
            system('exit');
            die;
        }
    }
    
    Login or Signup to reply.
  2. $_SERVER['argv'] = [ 'strlen' ];
    
    // Remove empty values in $_SERVER['argv'].
    // Since all entries in _SERVER are strings it removes entries being '' and '0'.
    $args = array_filter($_SERVER['argv']);
    
    // Alternatively if for example '0' should not be removed
    $args = array_filter($_SERVER['argv'], fn($item) => $item !== '');
    // Or if for example the value should be trimmed first
    $args = array_filter($_SERVER['argv'], fn($item) => trim($item) !== '');
    
    // Remove the first element
    $func = array_shift($args);
    
    if (function_exists($func)) {
        $func(...$args);
    } else {
        die('First argument is not a function');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search