PHPの抽象クラスはabstract class Nameで宣言し、newで作ることはできません。ほかのクラスの土台で、プロパティ、コンストラクタ、完成したメソッドに加え、すべての子クラスが実装しなければならない本体のないabstractメソッドを持てます。
<?php
abstract class Shape
{
public function __construct(protected string $label) {}
abstract public function area(): float;
public function describe(): string
{
return sprintf('%s: %.2f', $this->label, $this->area());
}
}
class Rectangle extends Shape
{
public function __construct(private float $w, private float $h)
{
parent::__construct('Rectangle');
}
public function area(): float
{
return $this->w * $this->h;
}
}
class Circle extends Shape
{
public function __construct(private float $r)
{
parent::__construct('Circle');
}
public function area(): float
{
return M_PI * $this->r ** 2;
}
}
foreach ([new Rectangle(3, 4), new Circle(1.5)] as $shape) {
echo $shape->describe(), "\n";
}
PHP Fatal error: Class Square contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Shape::area) in /home/index.php on line 3
<?php
interface Cache
{
public function get(string $key): mixed;
public function set(string $key, mixed $value): void;
public function has(string $key): bool;
}
abstract class BaseCache implements Cache
{
// has() is written once, in terms of get()
public function has(string $key): bool
{
return $this->get($key) !== null;
}
}
class ArrayCache extends BaseCache
{
private array $items = [];
public function get(string $key): mixed
{
return $this->items[$key] ?? null;
}
public function set(string $key, mixed $value): void
{
$this->items[$key] = $value;
}
}
$cache = new ArrayCache();
$cache->set('user:1', 'Ada');
var_dump($cache->has('user:1'), $cache->has('user:2'));
var_dump($cache instanceof Cache);