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

PHP : How to call method from other class without inheritance

我这里有个小问题,不好意思问了一个愚蠢的问题。

所以,我有 StoreCategories Class 其中有:

    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;
        }
    }

在我的 index.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);
    }

如您所见,我想设置不在 StoreCategories 中的卡 ID Class..

我有一张卡片 Class 是这样的 :

    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,但风险太大.. 有人有其他方法吗?

谢谢:)

您可以使用Traits

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

trait CardIdTrait {

    private $card_id;


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

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

}

并将Cardclass修改为:

class Card {
    use CardIdTrait;
}

class StoreCategories 
{
    use CardIdTrait;

    private $store_category_id;
    private $category;

    // ...
}