PHP getopt Operations

后端 未结 3 1662
梦如初夏
梦如初夏 2021-01-11 19:19

This question is regarding getopt function in php. I need to pass two parameter to the php scripts like

php script.php -f filename -t filetype
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-11 19:25

    If you just put something like this in your PHP script (called, on my machine, temp.php) :

    And call it from the command-line, passing those two parameters :

    php temp.php -f filename -t filetype
    

    You'll get this kind of output :

    array(2) {
      ["f"]=>
      string(8) "filename"
      ["t"]=>
      string(8) "filetype"
    }
    

    Which means that :

    • $file['f'] contains the value passed for -f
    • and $file['t'] contains the value passed for -t


    Starting from there, if you want your switch to depend on the option passed as the value of -t, you'll use something like this :

    switch ($file['t']) {
        case 'u':
                // ...
            break;
        case 'c':
                // ...
            break;
        case 'i':
                // ...
            break;
    }
    

    Basically, you put :

    • The variable that you want to test in the switch()
    • And the possible values in the cases


    And, for more informations, you can read, in the PHP manual :

    • The manual page of switch
    • And getopt()

提交回复
热议问题