[英]PHP inheritance and different parameters in childs
我正在尝试在 PHP 中创建类似于 generics 的东西。 我希望其他程序员能够创建自己支持的数据类型,所以我使用了称为 Fasade、Adapter 和 Factory 的设计模式。
我有一个主要的 class 是一个创建共享统一接口的具体对象的工厂。
工厂:
class ListFactory
{
public function __construct(private readonly array $listClasses) {}
public function create(string $type)
{
return new ($this->listClasses[$type]);
}
}
$listClasses变量理想地通过 DI 注入,并包含所有实现 ListInterface 的类,格式为['type' => 'className'] ...
所以现在我有一个接口,到目前为止只定义了一个方法:
列表接口:
interface ListInterface
{
public function add($item): static;
}
然后到目前为止,我有两个实现此接口的具体类:
整数列表:
class IntList implements ListInterface
{
private array $value = [];
public function add($item): static
{
if (!is_int($item)) { /* throw exception */}
$this->value[] = $item;
return $this;
}
}
字符串列表:
class StringList implements ListInterface
{
private array $value = [];
public function add($item): static
{
if (!is_strnig($item)) { /* throw exception */}
$this->value[] = $item;
return $this;
}
}
问题是如何做到这一点,以便我不必使用 if 验证数据类型,但我可以编写,例如,在 StringList class 中添加function,如下所示:
public function add(string $item): static
{
$this->value[] = $item;
return $this;
}
如果我现在尝试这样做,我会收到类似StringList 中的 add 方法的错误 class 必须与 ListInterface 中的 add 方法兼容
谢谢
签名必须与您说明的错误消息相匹配。 为了使该接口的每个添加 function 变得容易,您可以使用特征并在那里进行类型检查。
interface ListInterface {
public function add(mixed $item): static;
}
trait ListTrait {
public function add(mixed $item): static
{
switch(gettype($item)) {
case 'integer':
if(!$this instanceof IntList) throw new Exception("Int expected");
break;
case 'string':
if(!$this instanceof StringList) throw new Exception("String expected");
break;
}
$this->value[] = $item;
return $this;
}
}
class IntList implements ListInterface
{
use ListTrait;
private array $value = [];
}
class StringList implements ListInterface
{
use ListTrait;
private array $value = [];
}
示例用法
$i = new IntList();
$i->add(123);
$i->add("123"); // Exception!
$s = new StringList();
$s->add("123");
$s->add(123); // Exception!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.