PHP :如何在没有继承的情况下从其他类调用方法


PHP : How to call method from other class without inheritance

我这里有一个小问题,对不起,如果问一个愚蠢的问题。

所以,我有商店类别类,它有:

    class StoreCategories 
    {
        private $store_category_id;
        private $category;
        public function setStoreCategoryId($store_category_id)
        {
            $this->store_category_id = $store_category_id;
        }
        public function getStoreCategoryId()
        {
            return $this->store_category_id;
        }
        public function setCategory($category)
        {
            $this->category = $category;
        }
        public function getCategory()
        {
            return $this->category;
        }
    }

在我的索引中.php我像这样声明对象:

    $types = array();
    while($stmt->fetch())
    { 
       $type = new StoreCategories();
       $type->setCardId($card_id);
       $type->setStoreCategoryId($store_category_id);
       $type->setCategory($category);
       array_push($types, $type);
    }

如您所见,我想设置不在商店类别类中的卡ID。

我有这样的卡片类:

    class Card
    {
        private $card_id;

        public function setCardId($card_id)
        {
            $this->card_id = $card_id;
        }
        public function getCardId()
        {
            return $this->card_id;
        }
    }

我知道我可以Class Card extends StoreCategories用户来获取卡ID,但这风险太大。任何人都有其他方法可以做到这一点吗?

谢谢:)

您可以使用特征

将代码的公共部分移动到新trait

trait CardIdTrait {
    private $card_id;

    public function setCardId($card_id)
    {
        $this->card_id = $card_id;
    }
    public function getCardId()
    {
        return $this->card_id;
    }
}

并将Card类修改为:

class Card {
    use CardIdTrait;
}

class StoreCategories 
{
    use CardIdTrait;
    private $store_category_id;
    private $category;
    // ...
}
相关文章: