note 126899 added to language.attributes.overview

From: Date: Fri, 04 Mar 2022 05:22:01 +0000
Subject: note 126899 added to language.attributes.overview
Groups: php.notes 
Request: Send a blank email to php-notes+get-217682@lists.php.net to get a copy of this message
While the example displays us what we can accomplish with attributes, it should be kept in mind that the main idea behind attributes is to attach static metadata to code (methods, properties, etc.). This metadata often includes concepts such as "markers" and "configuration". For example, you can write a serializer using reflection that only serializes marked properties (with optional configuration, such as field name in serialized file). This is reminiscent of serializers written for C# applications. That said, full reflection and attributes go hand in hand. If your use case is satisfied by inheritance or interfaces, prefer that. The most common use case for attributes is when you have no prior information about the provided object/class. <?php interface JsonSerializable { public function toJson() : array; } ?> versus, using attributes, <?php #[Attribute] class JsonSerialize { public function __constructor(public ?string $fieldName = null) {} } class VersionedObject { #[JsonSerialize] public const version = '0.0.1'; } public class UserLandClass extends VersionedObject { #[JsonSerialize('call it Jackson')] public string $myValue; } ?> The example above is a little extra convoluted with the existence of the VersionedObject class as I wished to display that with attribute mark ups, you do not need to care how the base class manages its attributes (no call to parent in overriden method). ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.135 (proxied: 122.173.148.1) ---- Manual Page -- https://php.net/manual/en/language.attributes.overview.php Edit -- https://main.php.net/note/edit/126899 Del: integrated -- https://main.php.net/note/delete/126899/integrated Del: useless -- https://main.php.net/note/delete/126899/useless Del: bad code -- https://main.php.net/note/delete/126899/bad+code Del: spam -- https://main.php.net/note/delete/126899/spam Del: non-english -- https://main.php.net/note/delete/126899/non-english Del: in docs -- https://main.php.net/note/delete/126899/in+docs Del: other reasons-- https://main.php.net/note/delete/126899 Reject -- https://main.php.net/note/reject/126899 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#217682) next »