首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP面向对象设计

PHP面向对象设计
EN

Stack Overflow用户
提问于 2012-06-14 02:57:25
回答 1查看 588关注 0票数 1

我在设计我正在构建的一个小php应用程序的OOP时遇到了一些困难。我在数据库中有餐馆的信息,分为一个restaurant表和一个locations表。这两个表都有一些公共列,如phonewebsitelogo url。显然,locationsrestaurants之间的关系是多对一的.

所以问题是:我想创建一个Restaurant类,它包含所有与全球餐馆信息相关的信息,如名称、电话、网站、徽标等。然后,我想创建一个Location类,其中包含特定位置的信息,如地址、电话、网站、徽标等。

我遇到的问题是,我希望能够实例化这两种对象类型,但也希望Location类返回到父数据中,如果它本身不存在的话。通常,您可以编写这样的东西(缩写):

代码语言:javascript
复制
class Restaurant {

    protected $phone;

    function __construct($restaurant_id) {
        // Perform db call here and set class attributes
    }

    public function getPhone() {
        return $this->phone;
    }
}

class Location extends Restaurant {

    function __construct($location_id) {
        // Perform db call here and set class attributes

        // $restaurant_id would be loaded from the DB above
        parent::__construct($restaurant_id)
    }
}

$location = new Location(123);
echo $location->getPhone();

$restaurant = new Restaurant(456);
echo $restaurant->getPhone();

但正如我所说的,我希望getPhone()方法首先检查$this->phone,如果它不存在,则返回到父服务器。这样的事会不会是正确的方法?

代码语言:javascript
复制
class Restaurant {

    private $phone;

    function __construct($restaurant_id) {
        // Perform db call here and set class attributes
    }

    public getPhone() {
        return $this->phone;
    }
}

class Location extends Restaurant {

    private $phone;

    function __construct($location_id) {
        // Perform db call here and set class attributes

        // $restaurant_id would be loaded from the DB above
        parent::__construct($restaurant_id)
    }

    public function getPhone() {
        if(!empty($this->phone)) {
            return $this->phone;
        }
        return parent::getPhone();
    }
}

$location = new Location(123);
echo $location->getPhone();

我觉得上面的代码真的很麻烦,而且可能有更好的方法来实现这一点。由于这两个类都有共同的属性,所以Location类最好不要扩展Restaurant,而是为“父”对象保留一个Restaurant类型的变量?然后在Location::getPhone()方法中,它执行类似的if(empty())检查吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-14 02:59:52

Location不应该扩展Restaurant,因为它本身并不是一家餐厅;它是该餐厅的许多位置之一。

代码语言:javascript
复制
class Location {
    private $restaurant;
    private $phone;

    public function getPhone() {
        return $this->phone ?: $restaurant->getPhone();
    }
}

现在,在这两个类之间有这么多相同的字段,您可能希望定义一个它们各自扩展的公共基类,例如包含网站、电话和徽标的CompanyInfoHolder。在这种情况下,Location将完全覆盖上面的getPhone

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11026063

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档