简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM