dtgu21994537 2013-11-14 01:45
浏览 88

在PHP中更改本机getopt的已解析参数($ argv)

I have two PHP scripts for command line use:

  1. standalone.php: a standalone script using the native getopt() function.
  2. shell-loop.php: a shell-like interface that repeatedly reads a line, exits if necessary, otherwise passes the input with some additions defined in this 'shell'-environment to the standalone script called through inclusion

As the standalone script uses getopt() I would like to change the argument list it parses in the shell-loop script right before inclusion. I have tried setting $argv and $_SERVER['argv'] (argc respectively) to the new values but it seems getopt() does not read those variables, but - so I assume - it accesses the arguments passed to php directly. (Unless I made some silly mistake..)

So my question would be: can the argument list used by getopt() easily be altered from within a php script and how so? If not, for curiosity's sake, I would also wonder if there is a dirty way to do it?

shell-loop.php:

do {
    echo "> ";

    $cmd = trim(fgets(STDIN));

    if (in_array($cmd,array('exit','bye')))
    {
        break;
    }

    $argv = explode(' ',$cmd);

    // .. add some options here
    array_unshift($argv,'--option1');
    array_unshift($argv,'--option2');
    // ...

    $argc = count($argv);

    $_SERVER['argv'] = $argv; 
    $_SERVER['argc'] = $argc;

    // standalone.php relies on getopt() to get any optional parameters
    include __DIR__ . '/standalone.php';

} while(true);

and var_dump($GLOBALS) before the include (with actual arguments):

array(10) {
  ["GLOBALS"]=>
  *RECURSION*
  ["argv"]=>
  array(5) {
    [0]=>
    string(6) "bt.php"  <- inserted option
    [1]=>
    string(4) "--nl" <- inserted option
    [2]=>
    string(1) "-" <- inserted option
    [3]=>
    string(2) "on"
    [4]=>
    string(2) "A1"
  }
  ["argc"]=>
  &int(5)
  .. GET POST etc here ..
  ["_SERVER"]=>
  array(30) {
    .. many things here ..
    ["argv"]=>
    array(5) {
      [0]=>
      string(6) "bt.php"  <- inserted option
      [1]=>
      string(4) "--nl"  <- inserted option
      [2]=>
      string(1) "-"  <- inserted option
      [3]=>
      string(2) "on"
      [4]=>
      string(2) "A1"
    }
    ["argc"]=>
    int(5)
  }
}

The third-party getopt class as referenced here would do the job, yes.

I'll look up php's getopt implementation when I get the time, but thought it might be interesting to have the question answered here..

Structurally this approach makes sense in my case, but yes I could do it differently.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 基于单片机的靶位控制系统
    • ¥15 AT89C51控制8位八段数码管显示时钟。
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 下图接收小电路,谁知道原理
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错