Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I namespace global functions in PHP?

Tags:

namespaces

php

In PHP, I'm using namespaces at the class level. However, Netbeans keeps telling me namespace my global functions as well. For example, if I type

str_replace('stuff');

then Netbeans will suggest changing it to:

\str_replace('stuff');

Is this a PHP recommendation, or just Netbeans being overzealous? I haven't been able to find anything in the PHP documentation that says either way.

I can't see it causing any problems in the code. However, it feels wrong to just ignore Netbeans without knowing why it recommends it in the first place. But nor does it feel right just to change my coding practice without knowing it's the right thing to do.

like image 766
Dan Blows Avatar asked Mar 15 '12 14:03

Dan Blows


People also ask

How do I use global namespace?

By default, you can reference a globally namespaced class by adding a backslash -- eg $x = new \PDO(...); . Trying to use \ won't change that. If you want to drop the backslash from globally namespaced classes, you need to use each of them specifically.

Why namespaces are needed in PHP?

Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.

What is a global class in PHP?

Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.

What is the difference between namespace and use in PHP?

Namespace is to avoid class name collisions, so you can have two same class names under two different namespaces. Use is just like PHP include. Please sign in or create an account to participate in this conversation.


2 Answers

There is no such recommendation in

  • http://php.net/manual/en/language.namespaces.php

Nor is it necessary to use the global identifer since PHP will fallback to the global function definition when there is no function of that name in the current namespace.

With that said, the only reason to add the identifier is to make it more explicit that you want to use the actual global thing to prevent accidental changes in code behaviors when someone adds a function of the same name into the current namespace.

You might want to ask on the Netbeans Mailing List for more details about why your IDE suggests this.

like image 57
Gordon Avatar answered Oct 06 '22 02:10

Gordon


Overzealous for sure, but I can't reproduce this is Netbeans 7.0.1, with PHP Plugin 1.17.1. It's not the convention, anyway, and I would not consider it a best practice at all.

like image 26
Berry Langerak Avatar answered Oct 06 '22 02:10

Berry Langerak