23

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pus
  • 799
  • 4
  • 12
  • 35
  • 2
    Just to say that they are special (some of them, such as __get, __set and __call are called magic methods), and to avoid interfering with your own method names. – Artefact2 Mar 18 '11 at 06:11
  • Different [use of double underscores in some PHP frameworks](https://stackoverflow.com/questions/1777131/double-underscore-in-php/1777147#1777147), e.g. WordPress. (Not a duplicate.) – Peter Mortensen Feb 23 '22 at 14:20
  • Use of double underscores [in variable names](https://stackoverflow.com/questions/22576363/) (not a duplicate either). – Peter Mortensen Feb 23 '22 at 14:22
  • Though the WordPress way could be seen as an even more obscure way than the examples here (a special case). – Peter Mortensen Feb 23 '22 at 14:28

2 Answers2

34

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.

Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
  • What if the function name is empty (bare `__`)? [WordPress](https://stackoverflow.com/a/1777147) and [other frameworks use it](https://stackoverflow.com/a/22576411), seemingly violating the "reserves" part. This could be addressed in the answer (but ***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today).) – Peter Mortensen Mar 10 '22 at 16:32
  • And [in FuelPHP](https://stackoverflow.com/questions/25173085/what-does-the-function-do-in-fuelphp). – Peter Mortensen Mar 10 '22 at 16:39
  • And [in Twig](https://stackoverflow.com/questions/39969931/what-is-a-double-underline-for-in-twig-or-in-bolt). – Peter Mortensen Mar 13 '22 at 17:57
4

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

mario
  • 144,265
  • 20
  • 237
  • 291