Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why double underscore (__) in php?

Tags:

php

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?

like image 829
Pus Avatar asked Mar 18 '11 06:03

Pus


People also ask

What does double underscore mean in PHP?

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.

What starts with __ double underscore in PHP?

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.

What __ means in PHP?

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

What is double underscore in laravel?

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


2 Answers

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.

like image 96
Mike Lewis Avatar answered Sep 21 '22 14:09

Mike Lewis


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

like image 32
mario Avatar answered Sep 19 '22 14:09

mario