PHP:如何从没有继承的另一个类调用方法

时间:2015-01-15 19:07:44

标签: php class object

我在这里遇到一些问题,如果问一个愚蠢的问题,对不起。

所以,我有StoreCategories类,它有:

    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 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,但风险太大了.. 有没有其他方法可以做到这一点?

谢谢:)

1 个答案:

答案 0 :(得分:0)

您可以使用Traits

将代码的公共部分移动到新的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;

    // ...
}