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.
Using underscore in just for remembering purpose that we will not 'modify the variable'/'call the function' outside the class.
As we declare const variables in all uppercase so that while seeing the name of variable can guess that it is a const variable. Similar the variable that we don't want to modify outside the class, we declare it with underscore for our own convention.
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
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:
I believe your original assumption was correct, I have found it to be common practice for some languages to prefix an underscore to methods/members etc that are meant to be kept private to the "object". Just a visual way to say although you can, you shouldn't be calling this!
Simple using single and double underscore in class PHP
I know it from python, where prefixing your variables with an underscore causes the compiler to translate some random sequence of letters and numbers in front of the actual variable name. This means that any attempt to access the variable from outside the class would result in a "variable undefined" error.
I don't know if this is still the convention to use in python, though