Re: How to Get the Sub Classes of a Parent Class

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Mon, Oct 26, 2009 at 10:22 PM, Raymond Irving <xwisdom@xxxxxxxxx> wrote:

>
> This works if you know the name of the class. What I'm looking for is a way
> to get one of the sub classes and initialize it dynamically.
>
>
>
>
> ________________________________
> From: David Otton <phpmail@xxxxxxxxxxxxxxxxxxxxxxx>
> To: Raymond Irving <xwisdom@xxxxxxxxx>
> Cc: PHP-General List <php-general@xxxxxxxxxxxxx>
> Sent: Sun, October 25, 2009 10:25:27 AM
> Subject: Re:  How to Get the Sub Classes of a Parent Class
>
> 2009/10/25 Raymond Irving <xwisdom@xxxxxxxxx>:
>
> > I want to automatically initialize a specific sub class when the php page
> is loaded.
> >
> > I'm looking for a solution for php 5.1+ or anything that's optimized for
> 5.3
>
> You may be able solve this with a simple class_exists() (pseudo-code
> ahead):
>
> if(class_exists($var)) {
>    $class = new $var;
> } else {
>    $class = new FourOhFour;
> }
>

This script only works for loaded classes .
If your script has autoloader then there is no way to know the declared
classes before you declare them.

error_reporting( E_ALL | E_STRICT );

Class Foo {}

Class Bar extends Foo {}
Class Baz extends Foo {}

Class Beer extends Bar {}
Class Pier extends Bar {}

function get_subclasses($class)
{

    $sub = array();

    foreach(get_declared_classes() as $name )
    {
        $rClass = new ReflectionClass($name);

        if( $rClass->isSubclassOf( $class ))
        {
            $sub[] = $name;
        }
    }

    return $sub;
}

print_r( get_subclasses( 'Foo' ));
print_r( get_subclasses( 'Bar' ));

-- 
Martin Scotta

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux