PHP Named Arguments
Named arguments (PHP 8.0+) let you pass arguments by name instead of position, skip optional parameters, and make function calls self-documenting without needing to look at the signature.
<?php
// Traditional: must remember position and pass all params
$result = array_slice($array, 0, 5, true);
// Named: clear what each arg does, skip middle optionals
$result = array_slice(array: $array, offset: 0, length: 5, preserve_keys: true);
// Skip optional parameters completely
function createPost(
string $title,
string $content,
string $status = 'draft',
string $category = 'general',
bool $featured = false,
bool $comments = true
): array {
return compact('title','content','status','category','featured','comments');
}
// Old way: must pass all defaults explicitly to reach featured
$post = createPost('PHP Guide', 'Content here', 'draft', 'general', true);
// Named: jump straight to featured
$post = createPost(title: 'PHP Guide', content: 'Content here', featured: true);
// status='draft', category='general', comments=true (defaults kept)
PHP Attributes (Annotations)
<?php
// Attribute classes
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD)]
class Route {
public function __construct(
public string $path,
public string $method = 'GET'
) {}
}
#[\Attribute]
class Middleware {
public function __construct(public string $class) {}
}
// Using attributes
#[Route('/users', 'GET')]
#[Middleware(AuthMiddleware::class)]
class UserController {
#[Route('/users/{id}', 'GET')]
public function show(int $id): array {
return ['id' => $id];
}
#[Route('/users', 'POST')]
#[Middleware(ValidateMiddleware::class)]
public function store(array $data): array {
return $data;
}
}
// Reading attributes with Reflection
$ref = new ReflectionClass(UserController::class);
$attrs = $ref->getAttributes(Route::class);
foreach ($attrs as $attr) {
$route = $attr->newInstance();
echo $route->path . ' [' . $route->method . "]\n";
}
Q: What replaced PHPDoc annotations with PHP 8 Attributes?
PHPDoc annotations like @Route, @ORM\Column were strings in comments — PHP couldn't parse or validate them, frameworks had to parse them manually. Attributes are first-class PHP syntax, validated by the parser, readable via Reflection API without string parsing, and IDE/static-analysis friendly.
Comments (0)
No comments yet. Be the first!
Leave a Comment