Underscore in php function
Asked Answered
C

5

9

What does it mean when a PHP function name begins with an underscore?

for example: __construct()

I know what the construct means but I've seen other places where the function begins with an underscore, or a double underscore and I'm just not sure of the significance.

Cumbersome answered 30/11, 2009 at 16:49 Comment(0)
B
21

It means that PHP calls it implicitly.

It's called a 'Magic Method'

Also, it's two underscores, not one.

Learn more here: PHP Magic Methods

Beauteous answered 30/11, 2009 at 16:53 Comment(5)
Ah. Magic in PHP. Whatever next?Rb
I hate hate hate that they chose the term "magic" for this convention. It sounds so childish/idiotic. Why not just call them "hooks"?Prolific
@Amarghosh Who is everybody? Personally I like it and I know tons of people who like it.Special
@Peter Bailey: see catb.org/jargon/html/M/magic.html for a bit of explanationLashoh
@Amarghosh Do you mean everybody hate wordpress, everybody hate magento, everybody hate drupal, codeinginator, cakephp etc. Go out of you room lol i think everybody hate you... (^_~)Platas
S
5

In PHP, functions start with two underscores usually have special meanings. From the manual:

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.

For example __construct() is a special method which is called automatically while initializing an object.

Se also: http://php.net/manual/en/language.oop5.magic.php

Special answered 30/11, 2009 at 16:54 Comment(0)
R
4

There's also a common naming "coding style" which uses one initial underscore to indicate methods or properties are private/protected. I think it's pretty widespread.

Ralf answered 22/12, 2014 at 0:7 Comment(1)
Yes, I have used this in C#Marchelle
A
1

As noted in other answers, the double underscore is used for "magic" methods. The idea is that the user would never intentionally use two underscores for a method name, so there is little risk of collision. The reason it isn't a single underscore, I believe, is that the single underscore was a popular convention for private methods in the bad(der) old days, before the 'private' keyword came along to enforce OO privateness.

Allo answered 30/11, 2009 at 17:1 Comment(0)
E
0

In codeigniter, if you start a method in a controller with an underscore, the router will know not to allow it to be accessed from the url.

Etheridge answered 30/11, 2009 at 17:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.