Search code examples
phpclassoopinitialization

Is there a PHP equivalent to Python's __name__ == __main__?


I want to be able to write a script with all functionality encapsulated within a class and be able to also use the file as a script if invoked directly. Python offers this with the if __name__ == __main__ construct.

I searched the PHP docs for similar built-in variables and stackoverflow for previous mentions, but all corners came up empty. Posting this question on the off chance someone might know a way.

Does PHP have an equivalent?


Solution

  • There is a quick-and-dirty method:

    if ($argv[0] != ""){
       echo ("Started from the command line");
    }
    

    Explanation: if the file is started from the command line, then argv[0] is the filename itself, therefore not an empty string.

    When inserted with require(filename) then argv[0] is an empty string.