Why double underscore (__) in php?

后端 未结 2 1768
小鲜肉
小鲜肉 2021-02-07 00:53

Here are many functions with double underscores before the name:

__construct, 
__destruct, 
__call, 
__callStatic, 
__get, 
__set, 
__isset, 
__unset, 
__sleep,          


        
相关标签:
2条回答
  • 2021-02-07 01:39

    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.

    0 讨论(0)
  • 2021-02-07 01:41

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

    0 讨论(0)
提交回复
热议问题