从CLI运行脚本但阻止在包含时运行

时间:2012-01-01 15:38:02

标签: php command-line-interface

我有一个我经常使用CLI(常规ssh终端)运行的php脚本。

<?php

    class foo {
        public function __construct() {
            echo("Hello world");
        } 
    }

    // script starts here...
    $bar = new foo();

?>

当我使用php filename.php运行代码时,我得到Hello world停滞不前的预期。问题是当我从其他php文件中包含文件时,我得到了同样的东西(我不想要)。

如何在文件包含时阻止代码运行但仍将其用作CLI脚本?

3 个答案:

答案 0 :(得分:5)

您可以测试是否$argv[0] == __FILE__以查看从命令行调用的文件是否与包含的文件相同。

class foo {
    public function __construct() {

      // Output Hello World if this file was called directly from the command line
      // Edit: Probably need to use realpath() here as well..
      if (isset($argv) && realpath($argv[0]) == __FILE__) {  
        echo("Hello world");
      }
    } 
}

答案 1 :(得分:1)

你可以使用php函数get_included_files并检查你的文件是否在数组中(使用in_array)

http://php.net/manual/en/function.get-included-files.php

我希望这会对你有所帮助。

答案 2 :(得分:0)

您应该检查您是否已在CLI环境中运行而不是“包含”。请参阅下面我重写的示例:

<?php

    class foo {
        public function __construct() {
            echo("Hello world");
        } 
    }

    // script starts here...
    if (substr(php_sapi_name(), 0, 3) == 'cli'
        && basename($argv[0]) == basename(__FILE__) ) {

        // this code will execute ONLY if the run from the CLI
        // AND this file was not "included"
        $bar = new foo();

    }

?>