Pus
Pus

Reputation: 799

Why double underscore (__) in PHP function names?

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?

Upvotes: 23

Views: 20018

Answers (2)

mario
mario

Reputation: 145482

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

Upvotes: 4

Mike Lewis
Mike Lewis

Reputation: 64137

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.

Upvotes: 34

Related Questions