Using the @var Annotation in Adobe Commerce

I hope you’re making consistent use of PHP type-hinting for method arguments and return values in your Adobe Commerce code. Type-hinting makes your code more stable and predictable, shows up problems far earlier in the development process, and all but eliminates the need for cluttering your code with now-redundant annotations in comment blocks!

Consistent type-hinting also accelerates the usability of your IDE, allowing types to be inferred (and therefore useful features like code completion and auto-navigation made available) for just about any variables in your code. But don’t throw annotations completely out the window! You still ought to use them when types can’t be inferred automatically, and there are a couple of conspicuous use cases in Magento where you’ll always need them.

In phtml templates, there is no way for an IDE to infer the type of $block. You should make a habit of including a @var annotation for this value in every template you create.

The other common use case is for objects created by factories.

This one might be easy to forget, because your IDE will happily infer the type as long as the factory class does exist. But remember that factories are auto-generated classes and are not guaranteed to exist in your dev environment! When they haven’t yet been generated, or generated files have been cleared, your IDE will be left flailing to identify the type returned from create.

You’ll encounter plenty of other cases in Magento where @var will come in handy due to a lack of type-hinting. But these two cases are ubiquitous and more or less unavoidable. Making a habit of annotating types will not only power up your coding experience, but will also make context crystal clear for yourself and other developers when it’s been six months since you’ve laid eyes on the code!

Chris Nanninga

Director of Training and Development at SwiftOtter