174

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.

Neel
  • 854
  • 5
  • 7
nocash
  • 3,687
  • 4
  • 19
  • 12
  • 10
    Update 2014: It's officialy outdated syntax: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md – Sliq Apr 14 '14 at 17:16

14 Answers14

170

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.

Jeremy DeGroot
  • 4,496
  • 2
  • 20
  • 21
  • 12
    I place an underscore before methods in my controllers that are private to the class, and unused in routing. Because I work with my own framework, this adds security as I enforce the policy of no leading underscore on controller names within routes. But this rarely exceeds 1-2 methods per controller. – Robert K Jun 12 '09 at 03:33
  • 6
    By convention, with perl, method beginning with an underscore are private. But it's only a convention. In fact, these methods are still accessible from outside the class. – Luc M Apr 08 '10 at 19:11
  • Underscores make even less sense if an extending class decides to make its parent's protected method public. It's an edge case, but it happens. API developers may also choose to expose a private method as public, meaning they'd have to refactor the method name in addition to changing the access modifier. No biggie, but a nuisance nonetheless. – Johan Fredrik Varen Aug 31 '17 at 08:53
  • It's an C# convention that you can use, to prefix private members with exactly one underscore. Therefore it was an Zend Framework 1 (2012) convention to do it the same way. – alpham8 Sep 02 '19 at 08:37
  • Then why do I find this code in a WordPress plugin? - `public static $_instance;` Shouldn't it be `private $_instance;` or `private static $_instance`? – Dominik Jun 09 '21 at 12:05
77

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.

Tobske
  • 518
  • 3
  • 12
joedevon
  • 2,649
  • 4
  • 28
  • 43
  • 4
    When I first read about this, I understood the reason to be so that you can look at a method and know if it's public or private. Which would have made a whole lot more sense if it was a requirement rather than a convention. Because if 1 programmer on a team adds an underscore where unneeded, or makes public one with an underscore, you wind up with a whole lot of confusion. As it turns out, this came from PHP4 as Jeremy points out, & #ZF based their convention off of the PEAR convention. PEAR has removed it & I believe #ZF will follow suit. – joedevon Oct 16 '10 at 17:06
  • This answer is correct. It's all over the damn place in Magento, and as noted by Sliq below, it is a convention that has generally been deprecated. – siliconrockstar Feb 23 '15 at 18:34
  • Here is the updated link regarding this. http://framework.zend.com/manual/1.12/en/coding-standard.naming-conventions.html – Shapeshifter Jun 11 '15 at 16:51
  • FYI (and @joedevon) Zend 2.4 was released a few months back, and they still use underscore for private and protected http://framework.zend.com/manual/current/en/ref/coding.standard.html#functions-and-methods. – James Jun 20 '15 at 14:23
  • BUT Now Zend framework version 2.4 Does not use prefixed single underscore with `protected` and `private` variable or method declaration into Their code. Ex: `AbstractActionController` class -> https://github.com/zendframework/zend-mvc/blob/master/src/Controller/AbstractActionController.php OR `AbstractController` class -> https://github.com/zendframework/zend-mvc/blob/master/src/Controller/AbstractController.php – ahmed hamdy Sep 23 '15 at 13:33
43

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

Sliq
  • 15,937
  • 27
  • 110
  • 143
  • 7
    according to `PSR-2` -> "SHOULD NOT" mean "NOT RECOMMEND" not forbidden That mean in some case may be acceptable. PSR Doc -> http://www.ietf.org/rfc/rfc2119.txt – ahmed hamdy Sep 23 '15 at 13:11
14

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.

umpirsky
  • 9,902
  • 13
  • 71
  • 96
  • Yeah, agreed. I actually came here to see what others thought about underscores because I've only rarely used them, and it always feels wrong, but this example is one time I have. I've also used them for some cases of the template method pattern where a public method calls on abstract protected methods that children have overridden, which is a similar idea. *Sometimes* a public method and an abstract protected method that it calls are so similar or related that naming them differently seems weirder than just prefixing a _ to the abstract one. – John Pancoast Aug 04 '17 at 20:31
12

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

jonstjohn
  • 59,650
  • 8
  • 43
  • 55
10

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

GloryFish
  • 13,078
  • 16
  • 53
  • 43
9

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:

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

Community
  • 1
  • 1
m.ardito
  • 361
  • 3
  • 13
5

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!

Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
4

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

Matthew
  • 41
  • 1
3

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.

maho
  • 41
  • 3
  • 1
    I've considered that to be a design flaw of drupal for some time. It would make more sense to explicitly register your hooks to prevent confusion and erratic operation. Assumption is generally a bad thing, and constructs that interfere with normal programming or hijack them are usually poor architecture. – mopsyd Nov 15 '17 at 16:21
3

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

John Slegers
  • 45,213
  • 22
  • 199
  • 169
3

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.

Tassawer
  • 41
  • 4
0

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.

-22

They are called "magic methods".

  • 41
    `_foo()` with a single leading underscore is not a magic method. Magic methods are denoted by *two* consecutive leading underscores. The question here talks about only one. – BoltClock Sep 28 '10 at 15:33