Here are many functions with double underscores before the name:
__construct,
__destruct,
__call,
__callStatic,
__get,
__set,
__isset,
__unset,
__sleep,
__wakeup,
__toString,
__invoke,
__set_state
__clone
Why are these underscores used before these functions?
Strictly speaking, it means nothing in PHP as it is not a pre-defined function. However, in many frameworks, like CakePHP, and other libraries the double underscore is a function used for translating strings based on the user's language/locale preference.
PHP functions that start with a double underscore – a “__” – are called magic functions in PHP. They are functions that are always defined inside classes, and are not stand-alone functions.
__ in PHP is for magic methods like __get , __set , __clone. Historically _ before variable or function means it's private since there was no private, public or protected methods in PHP 4 . It is applied not only to PHP . In Python for example, _ prefix for functions and variables is used for the same purpose.
@froedrick double underscore is translation of the text. So, if you want to use multiple languages - you'll be able to easily define translations for this text. By default (if no translation defined for the current language) it will displays text as it is. 2. Level 50.
As stated here:
PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality
Long story short, PHP calls these functions implicitly and you shouldn't use this naming convention yourself.
Underscoritis. In PHP underscores have been used in various places, for example as prefix in the $_XYZ superglobals.
The method names you listed are magic methods. To make them look a bit more special they have been prefixed with two underscores. - That's what usually happens when the usage of one underscore as announcement is already too widespread. This naming pattern is not specific to PHP.
You can still define your own functions with two leading __
, but you shouldn't to avoid confusion with real magic methods or future language extensions. (Though that's not very probable.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With