How to programmatically find out what Magento 2 version in installed

There is a legacy (not recommended) solution with \Magento\Framework\AppInterface::VERSION constant:

It works in 2.0.0 and 2.0.1 by is already removed from the latest development version, so you should not rely on it.

The new solution is to use the \Magento\Framework\App\ProductMetadataInterface::getVersion()

By default it is implemented by the \Magento\Framework\App\ProductMetadata::getVersion()

Actually, lt looks at the root composer.json file:

A usage example

See also:

Magento 2.3 has removed its version information from the composer.json files since 2018-04-05.

I have updated my Magento version detection code for compatibility with Magento 2.3: