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
?
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.
***Follow the PSR-2 coding guideline:
Source: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
***Reason :
Source : http://www.geekgumbo.com/2013/05/19/psr-2-coding-style-guide/
Now, in 2013, this is "officially" bad style by the PSR-2 coding guideline:
Source: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
This is offical document from php.net say nothing about underscore stand before
private
methods,private
fields.But follow Zend Framework coding convention:
Therefore, we should start naming a
private
method with an underscore :)Notice:
( Source: http://php.net/manual/en/userlandnaming.rules.php )