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:33 PM, David Otton <
phpmail@xxxxxxxxxxxxxxxxxxxxxxx> wrote:

> 2009/10/27 Raymond Irving <xwisdom@xxxxxxxxx>:
>
> >>> I want to automatically initialize a specific sub class when the php
> page
> >>> is loaded.
>
> >> 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 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.
>
> I'm confused. If you don't know the name of the child class, how are
> you going to know which one to instantiate? Are you going to pick one
> at random?
>
> What you're trying to do can probably be accomplished, but I can't
> shake the feeling we're trying to solve the wrong problem here.
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>
Just having FUN, do not take me serious : )

function getInstanceRandom()
{
    $classes = get_declared_classes();
    $index = array_rand( $classes );
    return new $classes[ $index ]();
}

$obj = getInstanceRandom();
echo get_class( $obj );

This is way you NEVER know which class you will instantiate!

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