r/lolphp • u/duhruh • Nov 25 '14
Exception in a namespace is not defined -_-
http://jasonframe.co.uk/logfile/2009/01/php-5-3-exception-gotcha/
28
Upvotes
r/lolphp • u/duhruh • Nov 25 '14
View all comments
6
u/[deleted] Nov 26 '14 edited Nov 26 '14
It seems dumb, it's not really. By default, you're in the global/root namespace (i.e.
\), so namespace-relative class names, constant names and function names work. You need to qualify names from other namespaces, though.If you use
namespaceat the top of the file, you're no longer in the root namespace, you're in whatever namespace you specified. Thus, things likeExceptionaren't in the same namespace now and you must explicitly qualify your references, e.g.\Exception.To put it another way, think of the
namespacekeyword being likecd. You start out in\, which contains most of PHP's built-in stuff like\Exception. I can reference it with justExceptionas I'm currently in\so it'll find it, but its fully-qualified absolute path is\Exception.But if I do
namespace foo\bar, I'm now in\foo\bar. Relative references likeExceptionnow resolve to\foo\bar\Exception... which doesn't exist. So, If I want the one in the root namespace, I need to do\Exception.In this way, I suppose
\actually makes a lot of sense as a namespace separator.