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

PhpCoding Style

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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 - Php

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 - Php

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 - Php

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.

Solution 5 - Php

Leading underscores are generally used for private properties and methods. Not a technique that I usually employ, but does remain popular among some programmers.

Solution 6 - Php

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...

Solution 7 - Php

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:

>9. 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.

Solution 8 - Php

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!

Solution 9 - 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

Solution 10 - Php

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.

Solution 11 - Php

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...

Solution 12 - Php

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.

Solution 13 - Php

They are called "magic methods".

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnocashView Question on Stackoverflow
Solution 1 - PhpJeremy DeGrootView Answer on Stackoverflow
Solution 2 - PhpjoedevonView Answer on Stackoverflow
Solution 3 - PhpSliqView Answer on Stackoverflow
Solution 4 - PhpumpirskyView Answer on Stackoverflow
Solution 5 - PhpjonstjohnView Answer on Stackoverflow
Solution 6 - PhpGloryFishView Answer on Stackoverflow
Solution 7 - Phpm.arditoView Answer on Stackoverflow
Solution 8 - PhpQuintin RobinsonView Answer on Stackoverflow
Solution 9 - PhpMatthewView Answer on Stackoverflow
Solution 10 - PhpmahoView Answer on Stackoverflow
Solution 11 - Phpuser3613677View Answer on Stackoverflow
Solution 12 - PhpTassawerView Answer on Stackoverflow
Solution 13 - PhpTristanView Answer on Stackoverflow