PHP getopt 操作

标签 php file getopt

这个问题是关于 php 中的 getopt 函数的。我需要将两个参数传递给 php 脚本,例如

php script.php -f filename -t filetype

现在根据可以是 u、c 或 s 的文件类型,我需要进行适当的操作。

我正在使用 switch case:

这是我使用的代码:

// Get filename of input file when executing through command line.
$file = getopt("f:t:");

Switch case 应该比较我从命令行传入的文件类型(u、c 或 i),并相应地匹配它并执行操作。

switch("I am not sure what should go in there and this is wrong,Please advice")
    {

        case `Not sure`:
            $p->ini();
            break;

        case `Not sure`:
            $p->iniCon();
            break;

        case `Not sure`:
            $p->iniImp();
            break;
    }

请就此提出建议!!!

最佳答案

如果您只是将类似这样的内容放入您的 PHP 脚本中(在我的机器上称为 temp.php):

<?php
$file = getopt("f:t:");
var_dump($file);

然后从命令行调用它,传递这两个参数:

php temp.php -f filename -t filetype

你会得到这样的输出:

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

这意味着:

  • $file['f'] 包含为 -f
  • 传递的值
  • $file['']包含为-t
  • 传递的值


从那里开始,如果您希望您的 switch 依赖于作为 -t 的值传递的选项,您将使用如下内容:

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

基本上,你把:

  • 要在 switch() 中测试的变量
  • 以及case中的可能值


并且,有关更多信息,您可以阅读 PHP 手册:

关于PHP getopt 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2427176/

相关文章:

php - 使用 php 检查字符串是否包含 10 位数字但每个数字后有空格

php - Solr 与 MySQL 没有返回结果

java - Java 中的 Linux 文件锁定

c - 如何在 C 语言中获取文件的大小?

java - 为什么我得到 "null"作为输出字符串? java

c - 当选项是 C 上的字符串时如何使用 getopt?

haskell - Haskell 的 System.Console.GetOpt ReqArg 如何将 2 元函数作为其构造函数的第一个参数?

php - 向 WordPress 中的所有 url 添加一些参数

c - getopt() : Is optarg guaranteed to be non-NULL if optstring contains something like "a:"?

php - 如何在wordpress中插入自定义图像和html