簡體   English   中英

PHP inheritance 和孩子不同的參數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM