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

亚连
Release: 2023-03-26 11:44:01
Original
2606 people have browsed it

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
Copy after login

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
Copy after login

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;
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template