Use the exception error not found in the PHP namespace, with specific examples to explain to you in detail

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.