Drupal - When should I use methods, get() and magic offset

If there is a specific method - as for $node->getType() - I'd recommend using this one. Obviously that's never the case for dynamic stuff like fields - for that $node->type->value would be the recommendation.

Edit: $node->get('type') is just a more verbose variant of $node->type - both get you the "type" field object.


A specific method IMO is always preferred because of the @return typehint. You can't really typehint the return of a get('foo'). And, magic will always be slower and also an unknown to IDEs on what is returned. (Note that every time we are talking IDEs we are also talking possible bugs -- not just the IDE but the programmer has no knowledge of what's in a variable.)

Tags:

Entities

8