When a php file declares a namespace, the class must be specified in the namespace in which the file is used, otherwise it will be an error because the class is not found in the current space, and the PHP core class will have this problem, for example:
Namespace Testexc;try { throw new Exception (' throw Exception ');} catch (Exception $ex) { echo $ex->getmessage ();} 1234567
Run the above code, error:
PHP Fatal Error: Class ' testexc\exception ' not found in/private/var/folders/sr/1sh63qr542x9h61w4t7wrk200000gn/t/ Coderunner/untitled.php on line 61
From the error can also be seen, although exception is the PHP core class, but the program will only find in the current space exception class, there are two ways to solve
1. Declaring a exception that uses global space
Use \exception;
Used when exception is declared to use the global space
Namespace Testexc;try { throw new \exception (' throw Exception ');} catch (\exception $ex) { echo $ex GetMessage ();} 123456
Related knowledge:
If no namespace is defined, all classes and functions are defined in the global space, as before the introduction of the namespace concept in PHP. Precede the name with a prefix \ means that the name is the name in the global space, even if the name is in a different namespace.
For functions and constants, if the function or constant does not exist in the current namespace, PHP will fallback to use the function or constant in the global space.
Above is my collation to everyone on the PHP namespace error problem, I hope that in the future will be helpful to everyone.
Related articles:
About PHP namespaces (combined with code examples, simple and easy to understand)
PHP namespaces (combined with code detailed answers)
Combine code to detail scopes in PHP