That's just how namespaces work. Unless you are using the namespaced classes in the global namespace or they both have the same namespace, they will have to be imported.
Exception not found
Hi,
I'm making a class which is psr-4 autoloaded. The Class works as expected but at some point I want to throw an exception:
throw new Exception('Something wrong');
I get an error that the Class Exception is not found. So when I do this it works:
throw new \Exception('Something wrong');
Or I need to add:
use Exception;
My question: Is this normal behavior? Shouldn't it just work als in the first example?
@stefr imagine namespaces as folders, and each class as one file. And by default, PHP has some classes into the "root" of your app.
If you have a class MyClass in namespace App\SomeCustomName, that throws Exception in one of its methods, it would look like this:
namespace App\SomeCustomName;
class MyClass {
public function someMethod()
{
throw new Exception(); // this would try to throw new App\SomeCustomName\Exception
}
}
The key thing here and the one that makes the difference is - PHP will always look for a class within the same namespace (same folder), unless you precede it with a backslash, which tells PHP to start over from the root.
That being said, if you precede a classname with a \, you tell PHP "start over from the namespace root". And, by default, "in root" PHP has some of his own classes, such as Exception class, so the following code would work:
namespace App\SomeCustomName;
class MyClass {
public function someMethod()
{
throw new \Exception(); // this would look for Exception in the root, which is PHP's built-in Exception
}
}
Note: if you have
use Exception; // this is the full class name, together with the namespace, which in case of Exception is \ which we don't have to write on use statements
before the class declaration, then you don't have to do throw new \Exception in your code anymore as it's been imported.
Please or to participate in this conversation.