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

Ela*_*adG 2 php command-line-interface

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

<?php

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

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

?>
Run Code Online (Sandbox Code Playgroud)

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

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

Mic*_*ski 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");
      }
    } 
}
Run Code Online (Sandbox Code Playgroud)