Determining what classes are defined in a PHP class file

后端 未结 8 1350
-上瘾入骨i
-上瘾入骨i 2020-11-27 14:56

Given that each PHP file in our project contains a single class definition, how can I determine what class or classes are defined within the file?

I know I could jus

8条回答
  •  [愿得一人]
    2020-11-27 15:13

    If you just want to check a file without loading it use token_get_all():

    
    

    Basically, this is a simple finite state machine. In PHP the sequence of tokens will be:

    • T_CLASS: 'class' keyword;
    • T_WHITESPACE: space(s) after 'class';
    • T_STRING: name of class.

    So this code will handle any weird spacing or newlines you get just fine because it's using the same parser PHP uses to execute the file. If token_get_all() can't parse it, neither can PHP.

    By the way, you use token_name() to turn a token number into it's constant name.

    Here is my c2.php:

    
    

    Output:

    Found class: MyClass
    Found class: MyOtherClass
    

提交回复
热议问题