Home >Backend Development >PHP Tutorial >The problem of using Exception to report not found in the PHP namespace will be explained to you in detail with specific examples.

The problem of using Exception to report not found in the PHP namespace will be explained to you in detail with specific examples.

亚连
亚连Original
2018-05-17 14:53:322645browse

When a PHP file declares a namespace, when using a class in this file, you must specify which namespace it is in, otherwise an error will be reported because the class cannot be found in the current space, and the PHP core class cannot be found in the current space. There will be this problem. Example:

namespace TestExc;
try {    
throw new Exception('throw exception');
} 
catch(Exception $ex) 
{    
echo $ex->getMessage();
}1234567

Run the above code and the error will be reported:

PHP Fatal error:  Class 'TestExc\Exception' not found in /private/var/folders/sr/1sh63qr542x9h61w4t7wrk200000gn/T/CodeRunner/Untitled.php on line 61

You can also see from the error report that although Exception is a PHP core class, the program will only be in the current space. Looking for the Exception class, there are two solutions
1. Declare an Exception using the global space

use \Exception;

When using Exception, declare it as using 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, just like before PHP introduced the namespace concept. Prefixing a name with \ indicates that the name is in the global space, even if the name is in another namespace.

For functions and constants, if the function or constant does not exist in the current namespace, PHP will fall back to using the function or constant in the global space.

The above are the questions I compiled for you about PHP namespace error reporting. I hope it will be helpful to you in the future.

Related articles:

About PHP namespace (combined with code examples, simple and easy to understand)

PHP naming Space (detailed answer combined with the code)

Detailed introduction to the scope in php combined with the code

The above is the detailed content of The problem of using Exception to report not found in the PHP namespace will be explained to you in detail with specific examples.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn