Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the deal with a leading underscore in PHP class methods?

People also ask

Why use underscore in PHP?

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.

What is the correct way of initiating a PHP class?

Basic class definitions begin with the keyword class , followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. The class name can be any valid label, provided it is not a PHP reserved word.

Can PHP variable start with underscore?

A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )


It's from the bad old days of Object Oriented PHP (PHP 4). That implementation of OO was pretty bad, and didn't include things like private methods. To compensate, PHP developers prefaced methods that were intended to be private with an underscore. In some older classes you'll see /**private*/ __foo() { to give it some extra weight.

I've never heard of developers prefacing all their methods with underscores, so I can't begin to explain what causes that.


I believe the most authoritative source for these kinds of conventions for PHP right now would be the PSR-2: Coding Style Guide because the Zend Framework is part of PSR:

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


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


I was strongly against prefixing private/protected methods with underscore since you can use private/protected keyword for that and IDE will mark it for you.

And I still am, but, I found one reason why it can be a good practice. Imagine that you have public method addFoo() and inside that method you have some part of task which is common with other methods addFooWhenBar(), addFooWhenBaz()... Now, best name for that common method would be addFoo(), but it is already taken, so you must come up with some ugly name like addFooInternal() or addFooCommon() or ... but _addFoo() private method looks like best one.