Karl Johan Vallner
Karl Johan Vallner

Reputation: 4310

php abstract class extending method parameter type or type hint 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?

Upvotes: 0

Views: 1414

Answers (1)

fabrik
fabrik

Reputation: 14375

You could overcome this with implementing dependency inversion:

interface Blueprint {
}

class ParentBluePrint implements Blueprint
{
    public $id;
}

class ChildBluePrint extends ParentBlueprint
{
    public $id;
}

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

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

See more about relevant SOLID Principle here.

Upvotes: 0

Related Questions