note 126701 added to language.attributes.classes

From: Date: Wed, 22 Dec 2021 03:28:19 +0000
Subject: note 126701 added to language.attributes.classes
Groups: php.notes 
Request: Send a blank email to php-notes+get-217398@lists.php.net to get a copy of this message
#! Require PHP >= 8.0 #! This is a Sample <?php declare(strict_types = 1); #[Attribute] class Foo { function __construct(){ echo "Running " . __METHOD__ . PHP_EOL; } } #[Attribute(Attribute::TARGET_CLASS|Attribute::IS_REPEATABLE)] class Bar { function __construct(?string ...$args){ echo "Running " . __METHOD__ , " args: " . implode(", ", $args) . PHP_EOL; } } #[Attribute(Attribute::TARGET_ALL)] class Baz { function __construct( private string $parameter ){ echo "Running " . __METHOD__ , " arg: " . $this->parameter . PHP_EOL; } } #[Foo] // [0] #[Bar] // [1] #[Bar("Banana")] // [2] #[Bar("Banana", "Apple", "Lemon", "Grape")] // [3] #[Baz("The Only One")] // [4] class Qux { } // Getting class attribute with ReflectionClass $ref = new ReflectionClass(Qux::class); $attrs = $ref->getAttributes(); // Array of attributes $attrs[0]->newInstance(); // "Running Foo::__construct" $attrs[1]->newInstance(); // "Running Bar::__construct args: " $attrs[2]->newInstance(); // "Running Bar::__construct args: Banana" $attrs[3]->newInstance(); // "Running Bar::__construct args: Banana, Apple, Lemon, Grape" $attrs[4]->newInstance(); // "Running Baz::__construct arg: The Only One" ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.135 (proxied: 2804:431:c7d4:e026:cd8b:b4f4:1487:444e) ---- Manual Page -- https://php.net/manual/en/language.attributes.classes.php Edit -- https://main.php.net/note/edit/126701 Del: integrated -- https://main.php.net/note/delete/126701/integrated Del: useless -- https://main.php.net/note/delete/126701/useless Del: bad code -- https://main.php.net/note/delete/126701/bad+code Del: spam -- https://main.php.net/note/delete/126701/spam Del: non-english -- https://main.php.net/note/delete/126701/non-english Del: in docs -- https://main.php.net/note/delete/126701/in+docs Del: other reasons-- https://main.php.net/note/delete/126701 Reject -- https://main.php.net/note/reject/126701 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#217398) next »