mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-25 04:56:23 +00:00
50 lines
774 B
Markdown
50 lines
774 B
Markdown
|
---
|
||
|
id: 046ba725-37b9-4aca-837c-5d0cda679cc2
|
||
|
title: PHP Attributes
|
||
|
---
|
||
|
|
||
|
# Description
|
||
|
|
||
|
Introduced in [PHP 8.0](20201109133834-php_8_0). Attributes[^1] are a
|
||
|
way to add metadata to classes. Stitcher[^2] has an article that goes in
|
||
|
depth.
|
||
|
|
||
|
# Syntax
|
||
|
|
||
|
``` php
|
||
|
use App\Attributes\ExampleAttribute;
|
||
|
|
||
|
#[ExampleAttribute]
|
||
|
class Foo
|
||
|
{
|
||
|
#[ExampleAttribute]
|
||
|
public const FOO = 'foo';
|
||
|
|
||
|
#[ExampleAttribute]
|
||
|
public $x;
|
||
|
|
||
|
#[ExampleAttribute]
|
||
|
public function foo(#[ExampleAttribute] $bar) { }
|
||
|
}
|
||
|
```
|
||
|
|
||
|
``` php
|
||
|
#[Attribute]
|
||
|
class ExampleAttribute
|
||
|
{
|
||
|
public $value;
|
||
|
|
||
|
public function __construct($value)
|
||
|
{
|
||
|
$this->value = $value;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
```
|
||
|
|
||
|
# Footnotes
|
||
|
|
||
|
[^1]: <https://wiki.php.net/rfc/attributes>
|
||
|
|
||
|
[^2]: <https://stitcher.io/blog/attributes-in-php-8>
|