【问题标题】:PHP, parse all classes of a specific namespace, and list all methods of theses classesPHP,解析特定命名空间的所有类,并列出这些类的所有方法
【发布时间】:2018-10-17 07:50:29
【问题描述】:

我在特定目录中有一些类(例如 src/faa/foo),所有这些类都具有相同的命名空间(App\faa\foo)。

我正在寻找一种适当的方法来从 php 脚本中列出这些类的所有方法。

我想做这样的事情:

// list all class of this specific directory
$classes = get_all_class_by_directory_location('src/faa/foo');
// or
$classes = get_all_class_by_namespace('App\foo\faa');
    // but that means I must include theses classes to my script isn't it ? I think it's an ugly way because I only need print methods name, I don't need use them in this script 

foreach($classes as $class){
    print(get_methods($class));
}

做我想做的最好的方法是什么?它是否存在一个维护的社区 php 包来做到这一点?

我的项目遵循 psr-4 约定,也许这些信息有用..

【问题讨论】:

标签: php class oop


【解决方案1】:
<?php

foreach (glob('src/faa/foo/*.php') as $file)
{
    require_once $file;

    // get the file name of the current file without the extension
    // which is essentially the class name
    $class = basename($file, '.php');

    if (class_exists($class))
    {
        $obj = new $class;
        foreach(get_class_methods($obj) as $method)
        {
          echo $method . '\n';
        }
    }
}

取自:Create instances of all classes in a directory with PHP,然后添加了 get_class_methods 用法。

【讨论】:

    猜你喜欢
    • 2010-09-25
    • 2015-07-08
    • 2014-05-10
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    相关资源
    最近更新 更多