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
?
Variable naming rules PHP First, every variable must start with the special character $ . Variables can then start with an underscore ( _ ) or any letter, but not with a number or a special character. The names of your variables cannot contain special characters such as & , % , # , or @ .
Syntax of PHP Underscore reduce . In PHP, the underscore is generally reserved as an alias of gettext() (for translating strings), so instead it uses a double-underscore. All the functions that make up the library are available as static methods of a class called __ – i.e., a double-underscore. …and so on.
Internally, PHP itself uses Underscores for variables and functions, camelCase for Methods, and PascalCase for Classes, as stated in this PHP documentation page (userlandnaming. rules), and as spelled out in this PHP coding standards document.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
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.
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
***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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With