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

While looking over various PHP libraries I've noticed that a lot of people choose to prefix some class methods with a single underscore, such as

public function _foo()

...instead of...

public function foo()

I realize that ultimately this comes down to personal preference, but I was wondering if anyone had some insight into where this habit comes from.

My thought is that it's probably being carried over from PHP 4, before class methods could be marked as protected or private, as a way of implying "do not call this method from outside the class". However, it also occurred to me that maybe it originates somewhere (a language) I'm not familiar with or that there may be good reasoning behind it that I would benefit from knowing.

Any thoughts, insights and/or opinions would be appreciated.


Solution 1:

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.

Solution 2:

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.

Solution 3:

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

Solution 4:

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.