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.
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.
Leading underscores are generally used for private properties and methods. Not a technique that I usually employ, but does remain popular among some programmers.
I use a leading underscore in the PHP 5 class I write for private methods. It's a small visual cue to the developer that a particular class member is private. This type of hinting isn't as useful when using an IDE that distinguishes public and private members for you. I picked it up from my C# days. Old habits...
I was looking for the same answer, I did some research, and I've just discovered that php frameworks suggest different styles:
Code Igniter
The official manual has a coding style section that encourages this practice:
Private Methods and Variables
Methods and variables that are only accessed internally, such as utility and helper functions that your public methods use for code abstraction, should be prefixed with an underscore.
public function convert_text()
private function _convert_text()
Other frameworks do the same, like
Cakephp:
does the same:
Member Visibility
Use PHP5’s private and protected keywords for methods and variables. Additionally, non-public method or variable names start with a single underscore (_). Example:
class A
{
protected $_iAmAProtectedVariable;
protected function _iAmAProtectedMethod()
{
/* ... */
}
private $_iAmAPrivateVariable;
private function _iAmAPrivateMethod()
{
/* ... */
}
}
And also
PEAR
does the same:
Private class members are preceded by a single underscore. For example:
$_status _sort() _initTree()
While
Drupal
code style specifically warns against this:
Protected or private properties and methods should not use an underscore prefix.
Symphony
on the other hand, declares:
Symfony follows the standards defined in the PSR-0, PSR-1, PSR-2 and PSR-4 documents.
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!
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
In Drupal (a php CMS) underscores can be used to prevent hooks from being called (https://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7).
If I have a module called "my_module" and want to name a function my_module_insert it would "hook" on the function hook_insert. To prevent that I can rename my function to _my_module_insert.
ps
The way hooks works in Drupal it's possible to implement a hook by mistake, which is very bad.
Drupal, and using underscore:
In a general way the underscore is to simple mark the fact that a function would probably only be called by a related parent function...
function mymodule_tool($sting="page title"){
$out ='';
//do stuff
$out .= _mymodule_tool_decor($sting);
return $out;
}
function _mymodule_tool_decor($sting){
return '<h1>'.$string.'</h1>';
}
Of course, just a simple example...
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.
That means that this method is private.
"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." - it shouldn't be personal preference because every language or framework has it's own coding standards. Some FW coding standards is starting private methods with an _ and some FW discourage that.
You shoud use coding standard of a FW in which you program. To check if your code is according to the coding standard, you have a tool PHP_CodeSniffer: https://github.com/squizlabs/PHP_CodeSniffer
Very useful, detects errors regarding coding standard.
They are called "magic methods".
How do I document class constants for phpDoc? I've read the manual but I can't find anything about them.
Constants only need a docblock that contains the description. No specific tag is necessary. The code parser itself identifies constants and displays them as such in the generated documentation (here's an example).
I'm fairly sure that you can use #const, though I can't find any English documentation. There's a German example here. It shows define statements rather than class constants, but IIRC the syntax is the same.
Nine years later, an edit...
It is clear now that the above is bad advice as #const has not appeared in the docs and it seems it will not.
Using #var seems to work, though I cannot see it explicitly specified anywhere.
The full list of all PHPDoc 3 tags: Tag reference
The manual says the following:
#var
You may use the #var tag to document the Type of the following
Structural Elements:
Constants, both class and global scope
Properties
Variables, both global and local scope
Given the phpDoc manual, I cannot find explanation about that
#property-read
#property-write
but only of #property.
What do they do?
Here's a good explanation on magic properties.
Basically, #property-write is interpreted - as the name suggests - as a write-only property. The code completion in Eclipse, for example, makes use of this. If your magic property foo is declared "write-only", it wouldn't show up in code completion, when you type $a = $this->f.
The #property tag is what's documented in the phpDocumentor manual. This tag is used only in a class docblock to document a "magic" property/variable, i.e. one that is not defined in the code, and therefore can't be "docblock'd".
Now, when you want to highlight that a particular "magic variable" is read-only (not writable), you'd use #property-read. If you have a "magic variable" that is write-only (not readable), you'd use #property-write. Granted, I have trouble imagining write-only variables that can't be read, but since it's technically possible to do it, #property-write is available for you to document it.
These two "subtags" of #property are explained farther down on the #property page that you linked to above.
How can I mark up constants using PHPDoc? What #-tag should I use? I've thought of #var, but that's not appropriate.
The short answer is that there isn't one. And there doesn't need to be one either. The documentation generator is smart enough to be able to see the constant declaration. So just put the summary there without any #-tags. That should be all that you need to do...
class foo {
/**
* This constant does something that you need.
*/
const FOO = 'bar';
}
For constants, you use #type.
Is there a proper way to document a constant defined using define()? #var doesn't really make sense. The only thing I can think of is to omit the tag, and just write the description in the PHPdoc comment.
phpDocumentor does not recognize or utilize a #const tag. phpDocumentor recognizes a constant when it sees the "define" keyword in the code. Its output templates will show all constants in the output documentation, listed as constants. The only thing needed in the constant's docblock is a description, although many other "standard" tags are allowed if you feel like you need them [1].
[1] -- http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_elements.pkg.html#procedural.define
Use #const.
/**
* #const FOO Bar
*/
define('FOO', 'Bar');
Documentation (Sorry, the only docs I can find are in German.)
You actually want to use #type, see the Github PHP Documentation.