Topics Advanced PHP Features Attributes & Reflection
advanced 14 min read

Attributes & Reflection

PHP 8.0 attributes, creating custom attributes, and reflection API.

PHP Attributes (PHP 8.0+)

#[\Attribute]
class Route {
public function __construct(
public string \$path,
public string \$method = 'GET',
) { }
}

class UserController {
#[Route('/users', 'GET')]
public function index(): array {
return [];
}
#[Route('/users', 'POST')]
public function store(): array {
return [];
}
}

Reading Attributes

\$reflection = new ReflectionMethod(
UserController::class, 'index'
);
\$attributes = \$reflection->getAttributes(Route::class);
foreach (\$attributes as \$attribute) {
\$route = \$attribute->newInstance();
echo \$route->path; // /users
}

Examples

<?php
#[\Attribute]
class NotNull {}

class Validator {
    public function validate(object $obj): array {
        $errors = [];
        $ref = new ReflectionObject($obj);
        foreach ($ref->getProperties() as $prop) {
            if ($prop->getAttributes(NotNull::class) && $prop->getValue($obj) === null) {
                $errors[] = $prop->getName() . ' must not be null';
            }
        }
        return $errors;
    }
}

class User {
    #[NotNull]
    public ?string $name = null;
    public ?string $email = '[email protected]';
}
echo json_encode((new Validator())->validate(new User()));

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.