【发布时间】:2019-09-28 04:05:57
【问题描述】:
假设我有以下代码,有没有办法以某种方式扩展子类的抽象类并在“重载”函数中需要不同类型的参数。我想通过 add 函数在 Collection 中插入各种类型的对象。在某些情况下,我想插入一个 Error 对象,有时是一些其他 (XYZ) 对象,假设所有这些对象都扩展了同一个名为 Parent 的抽象类。
如果有人能告诉我这样的事情是否可能,我将不胜感激,如果它建议一些方法来实现这一点。请注意,我打算在其上托管应用程序的生产服务器在 php 5.6.40 上运行。
提前谢谢你。
namespace App;
use App\Models\Parent;
abstract class Collection
{
protected $collection;
public function __construct()
{
$this->collection = array();
}
abstract public function add($key, Parent $item);
}
public class ErrorList extends Collection
{
public function __construct()
{
parent::__construct();
}
public function add($key, Error $item)
{
$this->collection[$key] = $item;
}
}
namespace App\Models;
abstract class Parent {}
public class Error extends Parent {}
public class XYZ extends Parent{}
【问题讨论】:
-
不定义类型:abstract public function add($key, $item);
-
不过,如果我把
abstract public function add($key, $item)放上去会抛出两个函数不兼容的致命错误因为我在子类中要做的是public function add($key, Error $item){...} -
不要在子类中定义类型,它应该可以工作
-
Furthermore the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same.来源:php.net/manual/en/language.oop5.abstract.php -
@Marino Bjelopera 为什么不避免对父类和子类进行类型提示 :: abstract class Collection { abstract public function add($key, $item); } 公共类 ErrorList 扩展集合 { 公共函数 add($key, $item){} }
标签: php class oop inheritance abstract