Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rectangle / Square LSP Example Violation in PHP
<?php
class Rectangle
{
private $_width;
private $_height;
public function getWidth()
{
return $this->_width;
}
public function setWidth($width)
{
$this->_width = $width;
}
public function getHeight()
{
return $this->_height;
}
public function setHeight($height)
{
$this->_height = $height;
}
}
class Square extends Rectangle
{
public function setWidth($width)
{
parent::setWidth($width);
parent::setHeight($width);
}
public function setHeight($height)
{
parent::setWidth($height);
parent::setHeight($height);
}
}
class LSPRectangeTest extends PHPUnit_Framework_TestCase
{
private function areaTest(Rectangle $rectangle)
{
$width = 5;
$height = 4;
$rectangle->setWidth($width);
$rectangle->setHeight($height);
$actualArea = $rectangle->getWidth() * $rectangle->getHeight();
$expectedArea = $width * $height;
$this->assertEquals($expectedArea, $actualArea);
}
public function testRectangleArea()
{
$rectangle = new Rectangle();
$this->areaTest($rectangle);
}
public function testSquareArea()
{
$square = new Square();
$this->areaTest($square);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment