2012-01-01 5 views
2

CLI(通常のssh端末)を使用して実行するPHPスクリプトがあります。私はphp filename.phpを使用してコードを実行すると、予想通り、私はHello worldが停滞取得CLIからスクリプトを実行しますが、含まれていると実行されないようにします

<?php 

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

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

?> 

。問題は、私が他のPHPファイルからファイルをインクルードすると、私は同じことを(私は欲しくない)得ることです。

ファイルインクルード時にコードが実行されないようにするにはどうすればよいのですか?CLIスクリプトとして使用するにはどうすればよいですか?あなたのファイルは、アレイ内にある場合(in_array使用)

答えて

5

$argv[0] == __FILE__の場合は、コマンドラインからformというファイルがインクルードされたファイルと同じかどうかを調べることができます。

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

    } 

?> 
関連する問題