2012-01-01 62 views
2

我有一個PHP腳本,我經常使用CLI(普通SSH終端)運行。從CLI運行腳本,但阻止運行時,包括

<?php 

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

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

?> 

當我運行使用php filename.php代碼中,我得到了停滯的預期Hello world。問題是,當我從其他PHP文件中包含文件時,我得到了同樣的東西(我不想要)。

如何防止代碼在文件包含時運行,但仍將其用作CLI腳本?

回答

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"); 
     } 
    } 
} 
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(); 

    } 

?>