Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore method prefix

I've been examining the code of CodeIgniter and CakePHP and I noticed that some of the methods in their classes are prefixed with an underscore _ or a double underscore __.

What's the purpose of that?

like image 757
Emanuil Rusev Avatar asked Sep 21 '10 08:09

Emanuil Rusev


People also ask

What does _ and __ mean in Python?

Enforced by the Python interpreter. Double Leading and Trailing Underscore( __var__ ): Indicates special methods defined by the Python language. Avoid this naming scheme for your own attributes. Single Underscore( _ ): Sometimes used as a name for temporary or insignificant variables (“don't care”).

What is __ called in Python?

testFile.py. The Python interpreter modifies the variable name with ___. So Multiple times It uses as a Private member because another class can not access that variable directly. The main purpose for __ is to use variable /method in class only If you want to use it outside of the class you can make it public. Python3.

Why some variables start with _?

Many programmers use it to differentiate private variables - so instance variables will typically have an underscore prepended to the name. This prevents confusion with local variables.

Can we use underscore in method name?

Method names should always begin with a lower case character, and should not contain underscores.


2 Answers

In the case where it is not any of PHP's magic methods, it is to indicate Visibility in lack of proper Visibility keywords:

Cake Coding Conventions:

As we cannot use PHP5's private and protected keywords for methods or variables, we agree on following rules:

  • A protected method or variable name start with a single underscore ("_").
  • A private method or variable name start with double underscore ("__").

CodeIgniter conventions:

Methods and variables that are only accessed internally by your class, such as utility and helper functions that your public methods use for code abstraction, should be prefixed with an underscore.

like image 61
Gordon Avatar answered Sep 19 '22 15:09

Gordon


These are Magic Methods in PHP classes:

The function names __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state and __clone are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

A method with one underscore has no special meaning. This is more likely some coding convention of the projects.

like image 26
Felix Kling Avatar answered Sep 18 '22 15:09

Felix Kling