0

Let's say I have a class like:

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

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

And a child class like:

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

And:

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)?

Bugs
  • 1,422
  • 1
  • 14
  • 22
ceradon
  • 73
  • 1
  • 8
  • do you mean if there is a way to find out which child class is in use? – galchen Aug 25 '12 at 00:18
  • I believe this answers your question: http://stackoverflow.com/questions/6671398/get-all-defined-classes-of-a-parent-class-in-php – Bugs Aug 25 '12 at 00:19
  • No, return an array of instances of all of the children of the father class. Is that possible? – ceradon Aug 25 '12 at 00:20
  • 2
    No, it is not possible, and you shouldnt need to. – Green Black Aug 25 '12 at 00:20
  • 1
    @John tecnically you could iterate over `get_defined_vars()` and check if they are subclasses of given class - though I don't know how useful it would be. – moonwave99 Aug 25 '12 at 00:26
  • @moonwave Yes, you are right. Nice method :-) – Green Black Aug 25 '12 at 00:28
  • It's useful because I'm creating an IRC bot and this is a way to efficiently load plugin. Each plugin class will have a "hooks" function that will return the names of all the hooks that can be used to call the command. When one of the hooks match the the hook called the bot will initiate an instance of the class which the hook would call. – ceradon Aug 25 '12 at 00:39

1 Answers1

1

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);

And check the results.

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

moonwave99
  • 21,957
  • 3
  • 43
  • 64