Get class name from file

后端 未结 10 1859
轮回少年
轮回少年 2020-12-08 10:29

I have a php file which contains only one class. how can I know what class is there by knowing the filename? I know I can do something with regexp matching but is there a st

10条回答
  •  长情又很酷
    2020-12-08 11:06

    You can make PHP do the work by just including the file and get the last declared class:

    $file = 'class.php'; # contains class Foo
    
    include($file);
    $classes = get_declared_classes();
    $class = end($classes);
    echo $class; # Foo
    

    If you need to isolate that, wrap it into a commandline script and execute it via shell_exec:

    $file = 'class.php'; # contains class Foo
    
    $class = shell_exec("php -r \"include('$file'); echo end(get_declared_classes());\"");    
    echo $class; # Foo
    

    If you dislike commandline scripts, you can do it like in this question, however that code does not reflect namespaces.

提交回复
热议问题