1. 程式人生 > >php CLI 模式下的傳參方法

php CLI 模式下的傳參方法

在CLI模式(命令列介面 Command Line Interface)下,傳入引數有如下3種方法:

一. getopt函式(PHP 4 >= 4.3.0, PHP 5)

getopt — 從命令列引數列表中獲取選項

該函式會匹配傳入指令碼以單個連字元(-)或(--)開頭的選項,將其轉化為關聯陣列。

建立檔案:test1.php 程式碼如下

<?php $opt= getopt('m:n:'); print_r($opt); ?>

然後執行命令 php test1.php -maaaaaa -nbbbbbbb 結果如下: array( [m] => aaaaaa [n] => bbbbbbb )

二. $argv

建立檔案:test2.php 程式碼如下

<?php var_dump($argv); ?>

然後執行命令

php test2.php 1 2 3 a b c 結果如下: array(7){ [0]=>string(9) “test2.php” [1]=>string(1) “1″. [2]=>string(1) “2″ [3]=>string(1) “3″ [4]=>string(1) “a” [5]=>string(1) “b” [6]=>string(1) “c” }

三. STDIN

建立檔案:test3.php 程式碼如下

<?php fwrite(STDOUT, "Enter your name: "); $name = trim(fgets(STDIN)); fwrite(STDOUT, "Hello, $name!"); ?>

然後執行命令

php test3.php

結果如下:

此時螢幕輸出:Enter your name: 我們在後面輸入:111然後回車 此時螢幕會出現hello,111