- in_array: documentation ( source)
<?php
#[Attribute()]
final class Sealed {
public array $permitted = [];
public function __construct(string ...$permitted)
{
$this->permitted = $permitted;
}
}
function validate(string $classname): void
{
$class = new ReflectionClass($classname);
$validate_against = static function($parent) use($classname) {
if ($sealed = $parent->getAttributes(Sealed::class)) {
if (!in_array($classname, $sealed[0]->newInstance()->permitted, true)) {
throw new Error($classname.' cannot inherit from sealed class '.$parent->getName());
}
}
};
if ($parent = $class->getParentClass()) {
$validate_against($parent);
}
foreach($class->getInterfaces() as $interface) {
$validate_against($interface);
}
foreach($class->getTraits() as $trait) {
$validate_against($trait);
}
echo 'ok';
}
#[Sealed(Bar::class)]
interface Foo
{
}
final class Bar implements Foo {}
final class Baz implements Foo {}
validate(Bar::class);
validate(Baz::class);