Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
<?php abstract class Shape { public function __construct(protected string $color = 'black') {} // Subclasses MUST implement these abstract public function area(): float; abstract public function perimeter(): float; // Concrete method — shared by all shapes public function describe(): string { return sprintf( '%s %s — Area: %.2f, Perimeter: %.2f', ucfirst($this->color), static::class, // late static binding $this->area(), $this->perimeter() ); } } class Circle extends Shape { public function __construct(private float $radius, string $color = 'red') { parent::__construct($color); } public function area(): float { return M_PI * $this->radius ** 2; } public function perimeter(): float { return 2 * M_PI * $this->radius; } } class Rectangle extends Shape { public function __construct( private float $width, private float $height, string $color = 'blue' ) { parent::__construct($color); } public function area(): float { return $this->width * $this->height; } public function perimeter(): float { return 2 * ($this->width + $this->height); } } $shapes = [new Circle(5), new Rectangle(4, 6)]; foreach ($shapes as $shape) { echo $shape->describe() . " "; } // new Shape(); // Fatal Error: Cannot instantiate abstract class
Result
Open