Home > php教程 > php手册 > body text

如何正确实现PHP命令行读取参数

WBOY
Release: 2016-06-13 11:10:38
Original
877 people have browsed it

如果想实现PHP命令行读取参数,CLI可以从$_SERVER['argc']和$_SERVER['argv'']取得参数的个数和值。我们再建立一个文件,名字为testargs.php,脚本代码如下:

  1. #!C:phpphp.exe –q  
  2.  ?php  
  3. //UNIX和Linux平台下应该为
    #!/usr/local/bin/php –q  
  4. echo "测试获取参数:n";  
  5. echo $_SERVER["argc"]."n";  
  6. //显示传入的参数值,从索引1开始显示  
  7. echo $_SERVER["argv"][1]."n";  
  8. echo $_SERVER["argv"][2]."n";  
  9. echo $_SERVER["argv"][3]."n";  
  10. echo $_SERVER["argv"][4]."n";  
  11. ?> 

在命令行输入如下代码:

C:UsersJohn>testargs.php Always To Be Best

测试获取参数:

4
Always
To
Be
Best

因为我们输入了一串单词,为“Always To Be Best”,脚本参数以空格分隔。因此,PHP将其计为4个参数,下面对此说明。

$_SERVER["argc"]数组返回一个整型的数,代表从命令行上回车后一共输入了几个参数。

从PHP命令行读取参数范例中的结果已经看出,要访问已经传入的参数值,需要从索引1开始。因为脚本本身的文件已经占用了索引0,即$_SERVER["argv"][0]。


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template