【问题标题】:Is this a LSP violation (php)?这是违反 LSP 的 (php) 吗?
【发布时间】:2014-11-12 18:14:33
【问题描述】:
class Message {

    protected $body;

    public function setBody($body)
    {
        $this->body = $body;
    }

    public function getBody()
    {
        return $this->body;
    }
}

class ExtendedMessage extends Message {

    private $some;

    public function __construct($somedata) 
    {
        $this->some = $somedata;
    }

    public function getBody()
    {
        return $this->some;
    }
}

$a = new Message;

$b = new ExtendedMessage('text');

$a->getBody(); // NULL`

$b->getBody(); // text`

【问题讨论】:

标签: php oop design-patterns liskov-substitution-principle


【解决方案1】:

如果 $a 构造消息类,则 $body 为 NULL,因为没有对其进行任何设置,也没有 __construct() 触发(不存在)并将 $body 设置为某个值。

1 将 body 设置为某事 否则它将始终为 NULL

$a = new Message;
$a->setBody("my text here");
$a->getBody(); // returns "my text here"

2 向消息类添加构造函数

class Message {

    protected $body;

    public function __construct($a="") {
        $this->body = $a;
    }

    // ur code as shown
}

比跑

$a = new Message("my text");
$a->getBody(); // returns "my text"

$b = new Message;
$b->getBody(); // returns "" - emtpy string

3 在类def中将消息类中的正文设置为空字符串

protected $body = ""; // or whatever u want

它会在使用 getBody() 构造类后返回 val

【讨论】:

    猜你喜欢
    • 2013-06-15
    • 2017-03-17
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2016-03-28
    相关资源
    最近更新 更多