r/PHPhelp • u/[deleted] • Oct 24 '21
PHP8 Attributes
I understand the syntax, I understand using reflection to examine=ine them, I understand they replace annotations.
Nowhere can I see reasoning for their use. I am old, granted, but the received wisdom of my day was that reflection was bad - using up clock cycles at run time to determine “something” about your code meant that the code design was inefficient. Determining that “something” at coding time meant greater run-time efficiency.
So, can someone ELI5 (or indeed, ELI95) the rationale / use case for using attributes?
4
u/HolyGonzo Oct 24 '21
Attributes are just another layer of functionality in object-oriented programming.
A person who's first starting out with a career in construction or woodworking might wonder, "if any screw will attach two things together, then why do we need 100 different types of screws?" The answer is one that is learned over time as situations come up that would simply work a little bit better.
You -could- use properties instead of attributes but properties aren't meant to just be the catch-all for every situation.
For example, in a data model you probably want to use properties to correspond to data fields (e.g. $firstName property might hold the value for a "firstName" database field). So if you wanted to store some additional metadata about the class or properties, then storing that stuff in properties means you're now using properties to store different types of information.
It gets messy quick.
Attributes are ideal for storing metadata in a lightweight way that has virtually no impact on the class structure or functionality. For example, a common use of attributes in other languages is to control serialization/deserialization so you can say "if you're converting this class instance to XML or vice-versa, then class property 'newFoo' maps to the XML tag 'foo' and class property 'password' should be ignored".
Overall there are just lots of situations that come up where it's handy to have "flags" describing things like class properties and attributes are often great, non-intrusive ways of storing those flags.
1
u/HolyGonzo Oct 24 '21
And FWIW, reflection is very OFTEN bad, but not ALWAYS bad. It's usually bad when someone is using it as a workaround or a shortcut. I've built several code analysis tools in different languages and reflection is often a critical puzzle piece.
1
6
u/Mika56 Oct 24 '21
Attributes are better than annotations because they are interpreted by the php interpreter, which is faster than doctrine annotation (which is php code). Reflection can be bad if you're not using cache, but as far as symfony goes, most attributes/annotations are read when the cache is built, and never re-read after.