dimanche 23 septembre 2018

php type hinting extending variable type

Consider this case, I have an abstract class, which children take a blueprint and do different actions with it. Now I have multiple classes which extend this and perform slightly different actions with the blueprint, thus I have extended versions of said blueprint, which I need each of the child classes to get.

As such I want to define / type hint the property or respective function input property in the abstract class as any and then specify the property type in each of the child classes.

But I cannot do this, because PHP 7 gives me an error

Declaration B::setBlueprint() must be compatible with A::setBlueprint()

The blueprint classes

class Blueprint {
    public $id;
}

class ChildBlueprint extends ParentBlueprint {
    public $someOtherPropINeedOnlyInThisClass;
}

and the abstract classes that consume those blueprints

abstract class A {
    abstract public function setBlueprint( ParentBlueprint $_ );
}

class B extends A {
    public function setBlueprint( ChildBlueprint $_ ) {}
}

I mean I need a blueprint that is derived from the in all of the A, B, C, ..., X, Y classes and as such it makes no sense to leave it out of the abstract class.

What are good OOP solutions to this issue?

Aucun commentaire:

Enregistrer un commentaire