I've been examining the code of CodeIgniter and CakePHP and I noticed that some of the methods in their classes are prefixed with underscore _
/ double underscore __
.
What's the purpose of that?
I've been examining the code of CodeIgniter and CakePHP and I noticed that some of the methods in their classes are prefixed with underscore _
/ double underscore __
.
What's the purpose of that?
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.
They are probably magic methods. There is a number of those methods that serve a specific purpose (object constructor, object destructor, getter, setter...)
PHP reserves the __
prefix in function names for those magical functions. It's recommended not to define functions with that prefix for any other purpose.
Update: Both frameworks seem to use the __
prefix for their own purposes as well. See @Gordon's answer.
In the case where it is not any of PHP's magic methods, it is to indicate Visibility in lack of proper Visibility keywords:
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 ("__").
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.
I'm not familiar with CakePHP or CodeIgniter, but I think they should be regarded as protected
or private
for non-CakePHP classes. They are probably public
as they can be called from other classes, making some kind of hack. Please note that __get
, __construct
and other magic methods (as noted above) exists in PHP.
The methods that start with __ are magic methods which get called automatically in php. for more reference , check,