11

There are three different ways to get an entity value, for example the node content type.

  • $node->type->value
  • $node->getType()
  • $node->get('type')

Which one should I use?

10

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.

| improve this answer | |
5

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.)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.