benomite
benomite

Reputation: 868

php oop - transform an object to one of its children

Is it possible in PHP that a object transforms itself into one of his children class.

example

class Children1 extends Parent {
    // the children
}

class Parent {
    public function loadChildConfiguration($type){
        select($type){
            case 1: self::MAGICALLY_TRANSFORM_INTO(Children1); break;
            case 2: self::MAGICALLY_TRANSFORM_INTO(Children2); break;
            // etc...
        }
    }
}

$foo = new Parent();    // foo is a Parent
$foo->loadChildConfiguration(1);    // foo is now a Children1

For now the only idea I had was to create a static class in the parent as new constructor

class Parent {
    public static constructByType($type){
        select($type){
            case 1: $class = Children1; break;
            case 2: $class = Children2; break;
            // etc...
        }
        return new $class;
    }
}

$bar = Parent::constructByType(1);    // bar is a Children1

This should work as far as I do not need to get the children class after the parent creation.

Is there a way to change an object to its child after it has been created? Maybe there is another "cleaner" way to load new methods and parameter to an existing object?

Upvotes: 0

Views: 193

Answers (1)

STT LCU
STT LCU

Reputation: 4330

What you're actually looking for is something that abides to the so called "Factory Pattern"

You can find more details HERE

Basically you define a "factory" object which has the task to build the right type of object based on the specified needs (usually, you decide which object to build by calling a different method). Please note this is an overly broad semplification, i really suggest you to read the resource i linked you.

Also, you may want to take a look of another similar creational pattern, the "Builder Pattern" which, as the name suggests, is tasked with the creation of new objects.

More details HERE

PLEASE NOTE: Once you discover the design patterns, don't be struck in awe. They're merely tools, not the be-all and end-all of software developing. Basically, do USE design patterns, do not ABUSE (or over-use) design patterns! We have all been there and done that. Try not to follow us :D

Upvotes: 1

Related Questions