nayleen/attribute

提供访问单值 PHP 属性的访问器。

3.1.0 2023-03-06 22:42 UTC

This package is auto-updated.

Last update: 2024-08-26 18:28:31 UTC


README

提供访问 PHP 属性 的访问器。

安装

composer require nayleen/attribute

版本

为了便于使用,该库提供了两种访问属性值的方法

namespace Nayleen\Attribute;

// function
get(string|object $class, string $attribute, mixed $default = null): mixed;

// public static method
AttributeValueGetter::get(string|object $class, string $attribute, mixed $default = null): mixed;

使用方法

适用于实例和类名

use function Nayleen\Attribute\get;

#[Attribute]
class SomeAttribute
{
    public function __construct(private string $value) {}
}

#[SomeAttribute('foo')]
class MyClass {}

$value = get(MyClass::class, 'SomeAttribute'); // "foo"
$value = get(new MyClass(), 'SomeAttribute'); // "foo"

如果属性未设置,将抛出 MissingAttributeException 异常

get(MyClass::class, 'UnknownAttribute');
// uncaught Nayleen\Attribute\Exception\MissingAttributeException

除非您提供第三个参数作为默认值

get(MyClass::class, 'UnknownAttribute', 'foo'); // "foo"
get(MyClass::class, 'UnknownAttribute', 'bar'); // "bar"
get(MyClass::class, 'UnknownAttribute', 'baz'); // "baz"

对于重负载或懒加载,默认值可以是 callable

get(MyClass::class, 'UnknownAttribute', fn () => 'bar'); // "bar"

如果属性是可重复的,它将返回该属性值的数组

use function Nayleen\Attribute\get;

#[Attribute(Attribute::IS_REPEATABLE)]
final class RepeatableAttribute
{
    public function __construct(private string $value) {}
}

#[RepeatableAttribute('foo')]
#[RepeatableAttribute('bar')]
class MyClass {}

$value = get(MyClass::class, 'RepeatableAttribute'); // ["foo", "bar"]