Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- interface GeometricShape
- {
- public function getArea(): float;
- public function getPerimeter(): float;
- }
- class Rectangle implements GeometricShape
- {
- public function __construct(public float $length, public float $width)
- {
- ($length > 0 && $width > 0)
- or throw new ValueError('Length/width invalid');
- }
- public function getArea(): float
- {
- $result = $this->length * $this->width;
- is_finite($result)
- or throw new ValueError('Result is infinite');
- return $result;
- }
- public function getPerimeter(): float
- {
- $result = ($this->length + $this->width) * 2;
- is_finite($result)
- or throw new ValueError('Result is infinite');
- return $result;
- }
- }
- class Circle implements GeometricShape
- {
- public function __construct(public float $radius)
- {
- $radius > 0
- or throw new ValueError('Radius invalid');
- }
- public function getArea(): float
- {
- $result = ($this->radius * $this->radius) * pi();
- is_finite($result)
- or throw new ValueError('Result is infinite');
- return $result;
- }
- public function getPerimeter(): float
- {
- $result = ($this->radius * 2) * pi();
- is_finite($result)
- or throw new ValueError('Result is infinite');
- return $result;
- }
- }
- $eol = empty($argc) ? '<br>' : PHP_EOL; // determine end of line
- /* create shapes */
- $circle = new Circle(radius: 6);
- $rectangle = new Rectangle(width: 3.5, length: 12.7);
- /* output details about each shape */
- foreach ([$rectangle, $circle] as $shape) {
- $argsList = '';
- foreach (get_object_vars($shape) as $name => $value) {
- $argsList .= "$name: $value ";
- }
- printf('%s - %s' . $eol .
- ' Area: %s' . $eol .
- ' Perimeter: %s' . $eol . $eol,
- get_class($shape), $argsList,
- round($shape->getArea(), 3),
- round($shape->getPerimeter(), 3));
- }
Advertisement
Add Comment
Please, Sign In to add comment