zoukankan      html  css  js  c++  java
  • php 命名空间

    参考:http://php.net/manual/en/language.namespaces.definitionmultiple.php

    http://jingyan.baidu.com/article/f3e34a12a8dfc2f5eb6535ce.html

    php 的命名空间,defining mutiple namespaces in the same file.

    1. 多个命名空间写法要统一, 要么 namespace Ysr; 要么 namespace Ysr{}

    It is strongly discouraged as a coding practice to combine multiple namespaces into the same file.

    The primary use case is to combine multiple PHP scripts into the same file.

    2. 好的编码习惯并不建议将多个命名空间写在一个脚本文件当中。 将多个命名空间写在同一个脚本文件当中的做法一般只是当要 “include” 或者 "require" 其他文件进来的时候,这个时候会出现一个脚本文件中 有多个命名空间。

    3. 全局的代码 包含在 namespace 什么的代码块中, namespace 后面不用出现命名空间的名字。

    To combine global non-namespaced code with namespaced code, only bracketed syntax is supported. Global code should be encased in a namespace statement with no namespace name as in:

    <?php
    namespace MyProjectYSRhaha{
        const CONNECT_OK = 1;
        function var_dump(){
            echo 'ysr';
        }
    }
    
    
    
    namespace {
        use MyProjectYSRhaha;
        $a = 2;
        hahavar_dump($a);
    }
    
    namespace AnotherProject{
    
        const CONNECT_OK = 1;
        class Connection { /* ... */ }
        function connect() { /* ... */  }
    }
    

      4. 通过命名空间来调用函数

    //food.php
    
    <?php
    namespace Food;
    
    require ('Apple.php');
    require('Orange.php');
    
    use Apples;
    use Oranges;
    
    Appleseat();
    Orangeseat();
    ?>
    
        //Apple.php
        <?php
    namespace Apples;
    
    function eat()
    {
        echo "eat apple";
    }
    ?>
    
        //Orange.php
        <?php
    namespace Oranges;
    
    function eat()
    {
        echo "eat Orange";
    }
    ?>
    

      -------------------------------------------------------------------------------------------------------------

    5. 命名空间的别名运用。

    命名空间的别名,主要是用来正对命名空间比较长的情况, 还有就是命名空间导入类,函数和常量是不能用命名空间导入的(函数好像可以导入,这个有点疑问!!)。

    代码如下:

    <?php
    
    
    namespace MyProjectYSRhaha{
        const CONNECT_OK = 1;
        function var_dump(){
            echo 'ysr';
        }
    }
    
    
    
    namespace {
        use MyProjectYSRhaha;
        use AnotherProjectzzz;
        $a = 2;
        var_dump( zzzCONNECT_OK); //报错,
    //    var_dump( new zzzConnection());
    //    var_dump( zzzconnect());
    }
    
    namespace AnotherProjectzzz{
    
        const CONNECT_OK = 1;
        class Connection {
            public function __construct()
            {
                echo "come in";
            }
        }
        function connect() {
            echo "AnotherProject funciton ysr ";
        }
    }
    

      

  • 相关阅读:
    117. Populating Next Right Pointers in Each Node II
    50. Pow(x, n)
    494. Target Sum
    Word Ladder
    HDU 4417
    POJ 2104
    POJ 3277
    【转】图论500题
    POJ 2991
    POJ 1436
  • 原文地址:https://www.cnblogs.com/oxspirt/p/6042834.html
Copyright © 2011-2022 走看看