Home > Article > Backend Development > php defines multiple namespaces in the same file
Example #1 Define multiple namespaces, simple combination syntax
<?php namespace MyProject; const CONNECT_OK = 1; class Connection { /* ... */ } function connect() { /* ... */ } namespace AnotherProject; const CONNECT_OK = 1; class Connection { /* ... */ } function connect() { /* ... */ } ?>
It is not recommended to use this syntax to define multiple namespaces in a single file. It is recommended to use the following curly bracket form of syntax.
Example #2 Define multiple namespaces, brace syntax
<?php namespace MyProject { const CONNECT_OK = 1; class Connection { /* ... */ } function connect() { /* ... */ } } namespace AnotherProject { const CONNECT_OK = 1; class Connection { /* ... */ } function connect() { /* ... */ } } ?>
In actual programming practice, it is highly discouraged to define multiple namespaces in the same file. This method is mainly used to merge multiple PHP scripts into the same file.
To combine the code in the global non-namespace with the code in the namespace, you can only use the syntax in the form of braces. Global code must be enclosed in curly braces with a namespace statement without a name, for example:
Example #3 Define multiple namespaces and code not included in the namespace
<?php namespace MyProject { const CONNECT_OK = 1; class Connection { /* ... */ } function connect() { /* ... */ } } namespace { // global code session_start(); $a = MyProject\connect(); echo MyProject\Connection::start(); } ?>
In addition to the initial declare statement, naming There must be no PHP code outside the space brackets.
Example #4 Defining multiple namespaces and code not included in namespaces
<?php declare(encoding='UTF-8'); namespace MyProject { const CONNECT_OK = 1; class Connection { /* ... */ } function connect() { /* ... */ } } namespace { // 全局代码 session_start(); $a = MyProject\connect(); echo MyProject\Connection::start(); } ?>