将一组子级返回给 PHP 类? [英] Return an array of children to a PHP class?

查看:41
本文介绍了将一组子级返回给 PHP 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类:

class father {
    function __construct() {
        $msg = "Blah...\n";
        print $msg;
    }

    function doSomething() {
        $msg = get_class($this) . " does something...\n";
        print $msg;
    }
}

还有一个子类:

class child extends father {
    function __construct() {
        $this->doSomething()
    }
}

还有:

class eldest extends father {
    function __construct() {
        $this->doSomething()
    }
}

有没有办法返回父类的孩子(在这种情况下是孩子和最年长的)的当前实例的数组?

Is there a way to return an array of the present instances of the children of the father class (child and eldest in this case)?

推荐答案

如果你想得到每个扩展 father 的类,你应该通过 反射:

If you mean to get every class that extends father, you should have a trip around all declared classes via Reflection:

$subclasses = array();

foreach(get_declared_classes() as $class)
{

    $reflection = new ReflectionClass($class);  
    $reflection -> isSubClassOf('father') && $subclasses[] = $class;

}

var_dump($subclasses);

并检查结果.

如果您需要了解 instances,请遍历 get_defined_vars() - 但您为什么需要知道这一点?

if you need to know about instances, iterate over get_defined_vars() - but why do you need to know this?

这篇关于将一组子级返回给 PHP 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆