gpt4 book ai didi

PHP getopt 操作

转载 作者:可可西里 更新时间:2023-10-31 23:02:32 24 4
gpt4 key购买 nike

这个问题是关于 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com