2

I find that some protected variables in the Magento core come with an underscore prefix and some don't.

Also some parameters in di.xml do not have an underscore

<type name="Magento\Catalog\Helper\Product">
<arguments>        
    .....
    <argument name="productRepository" xsi:type="object">Magento\Catalog\Api\ProductRepositoryInterface\Proxy</argument>
</arguments>
</type>

This protected var $productRepository does not have an underscore. Is there any reason for this ?

13

Magento 2 follows the PSR-2 coding standard, which states:

4.2

Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.

4.3

Method names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.

The only reason that you will find protected properties (or methods) with leading underscores is if it is code ported from Magento 1 and not refactored yet. Magento 1 followed the Zend Coding Standard of Zend Framework 1:

For methods on objects that are declared with the "private" or "protected" modifier, the first character of the method name must be an underscore. This is the only acceptable application of an underscore in a method name. Methods declared "public" should never contain an underscore.

  • in future i should use variable not have underscore. Old code contain underscore will be remove soon right? – mrtuvn Jul 28 '16 at 13:44
  • Yes, that is how it should be – Fabian Schmengler Jul 28 '16 at 13:46
  • Strongly agreed with @FabianSchmengler, but recently I have noticed a very weird issue with MEQP2 (github.com/magento/magento-coding-standard). When I set up this and connected with PhpStorm, the phpcs gave me warning that Private variables must be prefixed with an underscore. Magento clearly indicated at devdocs.magento.com/guides/v2.3/coding-standards/… we must use MEQP2. Why this difference then? Need you views on this. – Adnan Nov 7 at 8:57

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.