我有一个经常使用 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 脚本时阻止代码运行?
最佳答案
您可以测试 $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");
}
}
}
关于php - 从 CLI 运行脚本,但在包含时阻止运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8693876/