Is this a LSP violation (php)?

86 views Asked by At
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`
1

There are 1 answers

0
UnskilledFreak On

if $a constructs the message class, $body is NULL cause nothing is set to it and no __construct() fires (not exists) and will set the $body to something.

1 set body to something otherwise it will always be NULL

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

2 add constructor to message class

class Message {

    protected $body;

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

    // ur code as shown
}

than run

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

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

3 set body in message class to empty string in the class def

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

and it will return the val after class construction with getBody()