PHP面向对象设计

时间:2012-06-14 02:57:26

标签: php oop polymorphism

我有点困难想出我正在构建的小型php应用程序的OOP设计。我有数据库中餐馆的信息,分为restaurant表和locations表。两个表都有一些常见列,例如phonewebsitelogo url。显然,locationsrestaurants之间的关系是多对一的。

所以这就是问题所在:我想创建一个Restaurant课程,其中包含与全球餐馆信息相关的所有信息,例如姓名,电话,网站,徽标等。然后我想制作一个{ {1}}包含地址,电话,网站,徽标等特定位置信息的类

我遇到的问题是我希望能够实例化两种对象类型,但是如果父数据本身不存在,也希望让Location类回退到父数据。通常情况下,您可以编写类似这样的内容(缩写):

Location

但就像我说的那样,我希望getPhone()方法首先检查$ this-> phone,如果它不存在,则回退到父级。这样的事情会是正确的吗?

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();

我觉得上面的代码真的很hacky,并且可能有更好的方法来完成这个。由于这两个属性具有共同属性,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()检查?

1 个答案:

答案 0 :(得分:2)

Location不应该延伸Restaurant,因为它不是餐馆本身;这是该餐厅的众多地点之一。

class Location {
    private $restaurant;
    private $phone;

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

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