Heim  >  Artikel  >  Backend-Entwicklung  >  PHP CLI 模式 (命令行模式的PHP)

PHP CLI 模式 (命令行模式的PHP)

WBOY
WBOYOriginal
2016-06-23 14:29:50703Durchsuche

在看这篇文章之间你需要将以下代码存为 *.reg 文件导入你的注册表,不过要记得将 D:""php5"" 修改为你的 PHP 路径
这样通过在PHP文件上点击右键,你的 PHP 程序就能以 CLI [Command Line Interface] 模式运行了
你可以参看这里获得一些帮助:http://www.tblog.com.cn/manual/php/features.commandline.html
复制内容到剪贴板

[HKEY_CLASSES_ROOT"*"shell"使用PHP运行(&R)]
@=”使用PHP运行(&R)”
[HKEY_CLASSES_ROOT"*"shell"使用PHP运行(&R)"command]
@=”cmd /K D:""php5""php.exe "”%1"”"

如果你不想添加注册表项目,你也可以在 cmd / shell 下输入以下命令来运行:
复制内容到剪贴板

$ php textcmd.php

在附件里你可以看到这段程序的代码,相信如果你会 PHP 的话,你已经能够根据这个程序扩展他来玩玩了

核心部分:
我们是通过 fgets(STDIN) 来获取到键盘输入的,至于为什么以及更多更详细的东西,大家就看上面给出的手册地址应该就能明白了


不禁有朋友要问,这个东西要来有什么用?

其实也没多大用,学习,好玩而已

但在工作中也有需要用到的时候,例如:清理项目目录中的无效文件,搜集项目中的资源…等等

在我开发的程序中,我还用他来更新程序的版本号,就像下面的代码:

//以下代码是在 textcmd.php Text_Command 中的一个方法
//Text_Command::_update($args)
     protected function _update ( $args )
     {
         if ( isset ( $args [ 0 ]) && strtoupper ( $args [ 0 ]) == ' version ' ) {
             $files = scan_files ( dirname ( dirname ( __FILE__ )) . ' /lib ' ) ;
             replace_deep (
                 $files ,
                 array (
                     ' $version$ ' ,
                     ' $update_time$ ' ,
                 ) ,
                 array (
                     ' v1.0.0 ' ,
                     date ( ' Y-m-d ' ) ,
                 )
             ) ;
             return ' Project doc comments update complete ' ;
         }
     }
//以下是我写的两个函数,以配合文件扫描及替换
function scan_files ( $dir )
{
     $basepath = $dir ;
     $dirs = scandir ( $dir ) ;
     $files = array () ;
     foreach ( $dirs as $dir ) {
         if ( substr ( $dir , 0 , 1 ) == ' . ' || $dir == ' Zend ' )
             continue ;
         if ( is_dir ( $basepath . ' / ' . $dir )) {
             $files [] = scan_files ( $basepath . ' / ' . $dir ) ;
         } elseif ( is_file ( $basepath . ' / ' . $dir )) {
             $files [] = $basepath . ' / ' . $dir ;
         }
     }
     return $files ;
}
function replace_deep ( array $files , $tag , $value )
{
     foreach ( $files as $file ) {
         if ( is_array ( $file )) {
             replace_deep ( $file , $tag , $value ) ;
         } elseif ( is_readable ( $file )) {
             $content = file_get_contents ( $file ) ;
             $content = str_replace ( $tag , $value , $content ) ;
             file_put_contents ( $file , $content ) ;
         }
     }
}

虽然用其他的程序也能实现同样的工作,但我还是选择了用 PHP,只是因我比较喜欢而已

源程序点击这里下载

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn