9

Is there any way how to avoid to using so often backslash ?

Now if i'm using namespace and calling something global inside it i have to use backslash:

namespace foo;
$a = new \my\name(); // instantiates "my\name" class
echo \strlen('hi'); // calls function "strlen"
$a = \INI_ALL; // $a is set to the value of constant "INI_ALL"

in that case code inside namespace become really ugly, is there any way how to avoid that situation ???

The example was taken from that url: http://www.php.net/manual/en/language.namespaces.faq.php

But my problem in that, if I need call some built in class from namespace i have to use backslash in front of the name, can I somehow avoid it ?

2
  • You do not need to prefix every built-in function of PHP. Commented Aug 28, 2012 at 10:22
  • namespace documentation is really bad Commented Aug 28, 2012 at 10:23

1 Answer 1

9

constants and functions from the global namespace do not have to be prepended with a backslash. PHP will fallback to the global namespace for those on it's own. There is a whole chapter in the PHP manual explaining this:

Inside a namespace, when PHP encounters a unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. […] For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.

Sign up to request clarification or add additional context in comments.

10 Comments

Yep, and what should I do with exceptions, for instance, or any other buil in classes ? like memcached etc... ? it does not work if I call it without backslash even php builded extension class. It means in code there are a lot of back slashes :(
@user1016265 an exception is neither a function, nor a constant but a class and the manual clearly states that class names resolve to the current namespace name so you have to prepend them or alias them on top of your script.
You do however need to add the backslash infront of "native" class like \Exception, \Memcached or you can choose to add: use \Exception; to the top of your file. Then you can use new Exception('..'); without the backslash.
@Gordon that PHP manual fully crap. What solution do you think better, what Michael suggested or manual described ? My opinion Michael suggestion better in 100%
@user1016265 what Michael describes is the same that I describe is the same that the Manual describes. We all describe the same thing because we bothered to read and understand the manual.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.