PHP 面向对象 : Get all declared classes which are have extended another parent class

标签 php

我需要获取所有扩展了另一个父类的声明类。

例如……

class ParentClass {

}

class ChildOne extends ParentClass {

}

class ChildTwo extends ParentClass {

}

class ChildThree {

}

我需要一个输出这个的数组:

array('ChildOne', 'ChildTwo')

我是 PHP OOP 的新手,但基于一些谷歌搜索,我想到了这个解决方案。

$classes = array();

foreach( get_declared_classes() as $class ) {
    if ( is_subclass_of($class, 'ParentClass') ){
        array_push($classes, $class);
    }
}

我想问的是,这是做我想做的事情的最佳实践,还是有更好的方法?全局范围将包含许多不是 ParentClass 子级的其他类。遍历所有声明的类是最好的方法吗?

编辑 (目的澄清):

我想以此实现的是实例化扩展父类的每个子类。

我想做 $childone = new ChildOne; $childtwo = new ChildTwo; 用于 ParentClass 的每个 child 。

最佳答案

您可以尝试在类的第一次加载时记录它的声明。 它假设您正在使用自动加载。

如果你不使用 composer 而使用自定义加载器:

这是最简单的方法:

$instanciatedChildren = array();//can be a static attribute of the A class 
spl_autoload_register(function($class)use($instanciatedChildren){
   //here the code you use 
   if(is_subclass_of($class,'A')){
       $instanciatedChildren[] = $class;
   }
 }

如果你使用 Composer :

你可以创建一个扩展 composer/src/Composer/Autoload/ClassLoader.php 的类 然后覆盖 loadClass 方法以添加上面给出的条件。然后注册您的新加载程序并注销旧加载程序。

关于PHP 面向对象 : Get all declared classes which are have extended another parent class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13587930/

相关文章:

PHP - 组合来自同一二维数组的 2 个元素

php - 元编程到几种输出语言

php - libphp7.so 需要 12.0.0 或更高版本

php - mysql连接成功但没有选择数据库?

php - 从项目目录加载自定义 Phing 任务

php - 如何安装定时任务

php - 在其他方法中使用来自 __construct() 的变量

php - 如何在codeigniter中使用JOIN显示两个表的结果?

php - 使用PHP备份MySQL数据库

php - 用于点和数字验证的正则表达式