PHP相当于Python的__name__==“__main__”?
2022-08-30 11:54:50
						根据标题,是否有PHP等效于?__name__ == "__main__"
对于通过命令行和 Web 请求执行的脚本,是否有一些内容是有效的,还是需要自定义函数?
对于那些不熟悉Python的人来说,允许你定义一个模块文件,并且还有一些东西允许你运行它,如果它是入口点。PHP 中的等效结构类似于以下内容:__name__ == "__main__"
// SomeClass.php
<?php
class SomeClass
{
    function doStuff() {
        echo "wahey!\n";
    }
}
// python, I know.
if (__name__ == "__main__") {
    $sc = new SomeClass;
    $sc->doStuff();
}
?>
// OtherClass.php
<?php
require_once("SomeClass.php");
class OtherClass
{
    public $yep;
}
?>
// command line:
php SomeClass.php     // outputs "wahey!"
php OtherClass.php    // outputs nothing
注意:zerkms的答案是最好的,但不太正确 - 它应该是:
if (!debug_backtrace()) {
    // do useful stuff
}
这比!count(debug_backtrace())快得多,它本身的速度大约是我涉及realpath()的解决方案的两倍。
 
					 
				 
				    		 
				    		 
				    		