PHP Conference Japan 2024

屬性語法

屬性語法有幾個部分。首先,屬性宣告一律以起始 #[ 和對應的結尾 ] 包圍。在其中,列出一個或多個屬性,以逗號分隔。屬性名稱是不合格、合格或完全合格的名稱,如<a href="language.namespaces.basics.php" class="link">使用命名空間基礎知識 中所述。屬性的引數是可選的,但以常用的括號 () 包圍。屬性的引數只能是字面值或常數運算式。可以使用位置和命名引數語法。

當透過 Reflection API 請求屬性執行個體時,屬性名稱及其引數會解析為一個類別,並且引數會傳遞給其建構函式。因此,應該為每個屬性引入一個類別。

範例 #1 屬性語法

<?php
// a.php
namespace MyExample;

use
Attribute;

#[
Attribute]
class
MyAttribute
{
const
VALUE = 'value';

private
$value;

public function
__construct($value = null)
{
$this->value = $value;
}
}

// b.php

namespace Another;

use
MyExample\MyAttribute;

#[
MyAttribute]
#[
\MyExample\MyAttribute]
#[
MyAttribute(1234)]
#[
MyAttribute(value: 1234)]
#[
MyAttribute(MyAttribute::VALUE)]
#[
MyAttribute(array("key" => "value"))]
#[
MyAttribute(100 + 200)]
class
Thing
{
}

#[
MyAttribute(1234), MyAttribute(5678)]
class
AnotherThing
{
}
新增筆記

使用者貢獻的筆記 1 則筆記

3
yarns dot purport0n at icloud dot com
11 個月前
我有一陣子沒注意到,但您可以建立屬性的子類別

https://3v4l.org/TrMTe

<?php

#[Attribute(Attribute::TARGET_PROPERTY)]
class
PropertyAttributes
{
public function
__construct(
public readonly ?
string $name = null,
public readonly ?
string $label = null,
) {}
}

#[
Attribute(Attribute::TARGET_PROPERTY)]
class
IntegerPropertyAttributes extends PropertyAttributes
{
public function
__construct(
?
string $name = null,
?
string $label = null,
public readonly ?
int $default = null,
public readonly ?
int $min = null,
public readonly ?
int $max = null,
public readonly ?
int $step = null,
) {
parent::__construct($name, $label);
}
}

#[
Attribute(Attribute::TARGET_PROPERTY)]
class
FloatPropertyAttributes extends PropertyAttributes
{
public function
__construct(
?
string $name = null,
?
string $label = null,
public readonly ?
float $default = null,
public readonly ?
float $min = null,
public readonly ?
float $max = null,
) {
parent::__construct($name, $label);
}
}

class
MyClass
{
#[
IntegerPropertyAttributes('prop', 'property: ', 5, 0, 10, 1)]
public
int $prop;
}

$refl = new ReflectionProperty('MyClass', 'prop');
$attributes = $refl->getAttributes();

foreach (
$attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
?>
To Top