Php namespace usage tutorial

Source: Internet
Author: User
The php namespace is introduced in the php Tutorial Module today. this is a new feature provided after php5.3, mainly to solve the naming conflict problem, use the namespace keyword to define php functions, variables, and classes in a namespace.

The php namespace is introduced in the php Tutorial Module today. this is a new feature provided after php5.3, mainly to solve the naming conflict problem, use the namespace keyword to define php functions, variables, and classes in a namespace. Note that no output is required before using namespace. Otherwise, the following error will be prompted:

(! ) Fatal error: Namespace declaration statement has to be the very first statement in the script in F: \ web \ zend \ exercise \ test. php on line3

The following php code: in the file. php file, a constant, a function, and a class are defined using namespace: (file1.php)


 

After defining a namespace, you must add the namespace name when using it. the following php code: (file2.php)


 ";echo MyProject\MyFunc()."
";echo MyProject\MyClass::MyMethod();?>

After the namespace is defined, different methods, variables, and classes can be used as long as they do not belong to the same namespace!

The namespace can have a multi-level mode, as shown below:

Namespace MyProject \ Sunname;

A php file can contain multiple namespaces, as shown in the following code: (file3.php)


 

In addition, you can also use the use keyword to import the namespace, as shown in the following php code:


 ";echo ns\MyFunc()."
";echo ns\MyClass::MyMethod();?>

Another idea is the _ NAMESPACE _ constant, which is used to return the name of the current NAMESPACE and may be useful during debugging! Welcome to view morePhp Tutorial


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.