Daily WTF: PHP “Annotations”

by jmorris 3. November 2012 21:08

Annotations or Attributes (Java vs. .NET/C#) are a means of decorating classes, methods and properties with additional metadata or declarative information. The annotations/attributes can then be queried at runtime via reflection and methods associated with them can be invoked.

Incredibly powerful and useful, they are quite common in various frameworks for tasks associate with say validating data associated with a class or property or for mapping properties on an entity to column names in a table in an RDBMS. There are many, many other uses as well.

Here is an example in C#: https://github.com/jeffrymorris/attributes-example

image

Note that in both Java and C#, annotations/attributes are a first class language construct. This is useful for many reasons, including improved readability and comprehension, they are type-safe, you can attach a debugger and step into them, etc.

Today I learned that PHP also has a form of annotations…well, sort of! It seems that a couple of PHP frameworks (Symphony 2 and Doctrine 2) have “implemented” them not as a language construct but as a hack via comments:

image

Folks, those aren’t comments…that is code that will get executed! Yuck, this is wrong in so many ways…especially since there is an RFC for adding annotations to PHP in the works: https://wiki.php.net/rfc/annotations.

Just because you can, doesn’t mean you should!

Tags:

rant

Jeff Morris

Tag cloud

Month List

Page List