PHP code example of nayleen / attribute

1. Go to this page and download the library: Download nayleen/attribute library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nayleen / attribute example snippets


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"

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"

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"]