About PHP underscore naming convention (as in “_me

2019-03-23 12:20发布

问题:

This is a sort of general inquiry I've been wondering about. I've noticed a lot of this through other people's code, and never really knew the actual reason, just followed the trends, so here goes.

How come some methods and properties are named with an underscore in front, and others aren't? For example, when specifically would one use function _method(), and when would one use function method(), or, in other words, private $_someVariable vs. private $someVariable?

回答1:

Most of the time, it's a throwback convention to PHP4 which didn't support visibility for properties or methods, and library developers used the _ to indicate something that should be considered private, and not to be accessed directly from outside of the class. PHP5 does have visibility, but the convention is still often maintained.



回答2:

Now, in 2013, this is "officially" bad style by the PSR-2 coding guideline:

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

Source: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md



回答3:

***Follow the PSR-2 coding guideline:

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

Source: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md

***Reason :

No underscores before the property name, like $_income, instead use $income. The underscore was used in some frameworks and can be confused with PHP magic variables.

Source : http://www.geekgumbo.com/2013/05/19/psr-2-coding-style-guide/



回答4:

This is offical document from php.net say nothing about underscore stand before private methods, private fields.

But follow Zend Framework coding convention:

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.

Therefore, we should start naming a private method with an underscore :)

Notice:

PHP reserves all symbols starting with __ as magical. It is recommended that you do not create symbols starting with __ in PHP unless you want to use documented magical functionality.

( Source: http://php.net/manual/en/userlandnaming.rules.php )