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?

4
  • 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, 2011 at 6:11
  • Different use of double underscores in some PHP frameworks, e.g. WordPress. (Not a duplicate.) Feb 23, 2022 at 14:20
  • Use of double underscores in variable names (not a duplicate either). Feb 23, 2022 at 14:22
  • Though the WordPress way could be seen as an even more obscure way than the examples here (a special case). Feb 23, 2022 at 14:28

2 Answers 2

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.

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

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.