PHP等同于Python的__name__ =="__main__"? [英] PHP equivalent of Python's __name__ == "__main__"?

查看:107
本文介绍了PHP等同于Python的__name__ =="__main__"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照标题,是否有PHP等同于__name__ == "__main__"?

As per the title, is there PHP equivalent of __name__ == "__main__"?

对于通过命令行和Web请求执行的脚本,是否都适用?或者需要自定义功能?

Is there something that would work for both scripts executed through the command line and through a web request, or would a custom function be needed?

对于不熟悉Python的人,__name__ == "__main__"允许您定义模块文件,并且如果它是入口点,还可以通过一些操作来运行它. PHP中的等效结构类似于:

For those unfamiliar with Python, __name__ == "__main__" allows you to define a module file, and also have some things that allow you to run it if it is the entry point. The equivalent structure in PHP would resemble this:

// 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的答案是最好的,但不太正确-应该显示为:


Note: zerkms' answer is the best, but is not quite right - it should read:

if (!debug_backtrace()) {
    // do useful stuff
}

这比!count(debug_backtrace())快得多,后者本身的速度是我涉及realpath()的解决方案的两倍.

This is significantly faster than !count(debug_backtrace()), which itself is about twice as fast as my solution involving realpath().

推荐答案

if (!count(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)))
{
    // some usefull stuff
}

查看 https://www.php.net/manual /en/function.debug-backtrace.php 有关debug_backtrace函数的更多详细信息

look at https://www.php.net/manual/en/function.debug-backtrace.php for more details on debug_backtrace function

这篇关于PHP等同于Python的__name__ =="__main__"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆