neil_pearce

GeometricShape

Feb 21st, 2023
1,129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.07 KB | None | 0 0
  1. <?php
  2. declare(strict_types=1);
  3.  
  4. interface GeometricShape
  5. {
  6.     public function getArea(): float;
  7.     public function getPerimeter(): float;
  8. }
  9.  
  10.  
  11. class Rectangle implements GeometricShape
  12. {
  13.     public function __construct(public float $length, public float $width)
  14.     {
  15.         ($length > 0 && $width > 0)
  16.         or throw new ValueError('Length/width invalid');
  17.     }
  18.  
  19.  
  20.     public function getArea(): float
  21.     {
  22.         $result = $this->length * $this->width;
  23.  
  24.         is_finite($result)
  25.         or throw new ValueError('Result is infinite');
  26.  
  27.         return $result;
  28.     }
  29.  
  30.  
  31.     public function getPerimeter(): float
  32.     {
  33.         $result = ($this->length + $this->width) * 2;
  34.  
  35.         is_finite($result)
  36.         or throw new ValueError('Result is infinite');
  37.  
  38.         return $result;
  39.     }
  40. }
  41.  
  42.  
  43. class Circle implements GeometricShape
  44. {
  45.     public function __construct(public float $radius)
  46.     {
  47.         $radius > 0
  48.         or throw new ValueError('Radius invalid');
  49.     }
  50.  
  51.  
  52.     public function getArea(): float
  53.     {
  54.         $result = ($this->radius * $this->radius) * pi();
  55.  
  56.         is_finite($result)
  57.         or throw new ValueError('Result is infinite');
  58.  
  59.         return $result;
  60.     }
  61.  
  62.  
  63.     public function getPerimeter(): float
  64.     {
  65.         $result = ($this->radius * 2) * pi();
  66.  
  67.         is_finite($result)
  68.         or throw new ValueError('Result is infinite');
  69.  
  70.         return $result;
  71.     }
  72. }
  73.  
  74.  
  75. $eol = empty($argc) ? '<br>' : PHP_EOL;  // determine end of line
  76.  
  77.  
  78. /* create shapes */
  79. $circle = new Circle(radius: 6);
  80. $rectangle = new Rectangle(width: 3.5, length: 12.7);
  81.  
  82.  
  83. /* output details about each shape */
  84. foreach ([$rectangle, $circle] as $shape) {
  85.     $argsList = '';
  86.     foreach (get_object_vars($shape) as $name => $value) {
  87.         $argsList .= "$name: $value ";
  88.     }
  89.  
  90.     printf('%s - %s' . $eol .
  91.            ' Area: %s' . $eol .
  92.            ' Perimeter: %s' . $eol . $eol,
  93.            get_class($shape), $argsList,
  94.            round($shape->getArea(), 3),
  95.            round($shape->getPerimeter(), 3));
  96. }
  97.  
Advertisement
Add Comment
Please, Sign In to add comment