Home >Backend Development >PHP Tutorial >php defines multiple namespaces in the same file

php defines multiple namespaces in the same file

伊谢尔伦
伊谢尔伦Original
2016-11-23 10:59:361236browse

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=&#39;UTF-8&#39;);
    namespace MyProject {
        const CONNECT_OK = 1;
        class Connection { /* ... */ }
        function connect() { /* ... */ }
    }
    namespace { // 全局代码
        session_start();
        $a = MyProject\connect();
        echo MyProject\Connection::start();
    }
?>


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