13

Why we declare some variables in PHP as like $_variablename?

Does _ define something?

Please help me to clear this up, thanks.

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
Bakiya Raj
  • 133
  • 1
  • 4
  • There is no *inherent* meaning to the underscore. It's individual developer's naming preference. – deceze Apr 09 '13 at 06:34
  • 2
    Leading underscores are generally used for private properties and methods. It was old practice in PHP when private methods was not implemented in PHP – Subodh Ghulaxe Apr 09 '13 at 06:38
  • No _ does not defines variable or function private it's a naming convention just to remind variable or function is private – Subodh Ghulaxe Apr 09 '13 at 07:00
  • 4
    This is not a duplicate... The linked post is talking about class methods and this one is for variables. This post confirm that it's the same convention for variables. – Simon Aug 01 '16 at 20:21

4 Answers4

12

It's a naming convention.

From the pear manual on naming conventions:

Private class members are preceded by a single underscore. For example:

$_status
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
6

The underscore does not mean that the variable is private. It is not necessary to use the underscore. It’s simply a naming convention that reminds the developer that the variable/property/method is either private or protected

For Example

// This variable is not available outside of the class  
private $_someVariable;  

class MyClass {  
   // This method is only available from within this class, or  
   // any others that inherit from it.   
   protected function __myFunction() {}  
}  

In the code above, the underscore is not what makes the variable or method private; the private/protected keyword does that.

Subodh Ghulaxe
  • 18,333
  • 14
  • 83
  • 102
1

It is not mandatory to use '_' or '__' in your code but it helps you to understand the variable/function access type by just seeing the name.

In some PHP frameworks you may see:

_ for protected variable/function

__ for private variable/function
kwelsan
  • 1,229
  • 1
  • 7
  • 18
-4

this is mainly used to declare global variable and to in function.. generally it is not compulsory to use '_' this

http://php.net/ check this