Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php抽象类扩展方法参数类型或类型提示类型_Php_Oop_Design Patterns - Fatal编程技术网

php抽象类扩展方法参数类型或类型提示类型

php抽象类扩展方法参数类型或类型提示类型,php,oop,design-patterns,Php,Oop,Design Patterns,考虑这个例子,我有一个抽象类,孩子们拿一个蓝图并用它做不同的动作。现在,我有多个类来扩展它,并使用blueprint执行稍微不同的操作,因此我有所述blueprint的扩展版本,我需要每个子类来获得这些版本 因此,我希望将抽象类中的属性或相应的函数输入属性定义为any,然后在每个子类中指定属性类型 但是我不能这样做,因为PHP7给了我一个错误 Declaration B::setBlueprint() must be compatible with A::setBlueprint() 蓝图课程

考虑这个例子,我有一个抽象类,孩子们拿一个蓝图并用它做不同的动作。现在,我有多个类来扩展它,并使用blueprint执行稍微不同的操作,因此我有所述blueprint的扩展版本,我需要每个子类来获得这些版本

因此,我希望将抽象类中的属性或相应的函数输入属性定义为any,然后在每个子类中指定属性类型

但是我不能这样做,因为PHP7给了我一个错误

Declaration B::setBlueprint() must be compatible with A::setBlueprint()
蓝图课程

class Blueprint {
    public $id;
}

class ChildBlueprint extends ParentBlueprint {
    public $someOtherPropINeedOnlyInThisClass;
}
以及使用这些蓝图的抽象类

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

class B extends A {
    public function setBlueprint( ChildBlueprint $_ ) {}
}
我的意思是,我需要一个从所有a,B,C,…,X,Y类中的派生的蓝图,因此,将其从抽象类中排除是没有意义的


对于这个问题,什么是好的OOP解决方案?

您可以通过实现依赖项反转来克服这个问题:

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 $_ ) {}
}

请参阅有关SOLID Principle的更多信息。

问题是B不应该接受Blueprint,因为它需要ChildBluePrint,因为它的一些独特属性。所以接受蓝图是误导性的,因为它实际上需要一个子蓝图。A和B都有一个蓝图,这是它们功能的基础,所以在B中对蓝图进行不同的命名是没有意义的,所以我可以为它的setter函数设置不同的参数类型。然而,所有的蓝图仍然共享90%的相同属性,因此在抽象的层面上,它们肯定是相互衍生的。