代码之家  ›  专栏  ›  技术社区  ›  ParisNakitaKejser

php5和名称空间?

  •  3
  • ParisNakitaKejser  · 技术社区  · 15 年前

    我在PHP中做了很多工作,但我从来没有真正理解PHP中的名称空间方法。有人能帮我吗?我在php.net的网站上读过,它的解释不够好,我在上面找不到例子。

    我需要知道如何在示例版本中生成代码。

    • 命名空间:示例
      • 类别:样本类别1
        • 功能:测试功能1
      • 类别:样本类别
        • 功能:测试功能
        • 功能:测试功能
    1 回复  |  直到 13 年前
        1
  •  4
  •   Michael Clerx    15 年前

    这样地?

    <?php
    
    namespace sample
    {
        class Sample_class_1
        {
            public function test_func_1($text)
            {
                echo $text;
            }
        }
    
        class Sample_class_2
        {
            public static function test_func_2()
            {
                $c = new Sample_class_1();
                $c->test_func_1("func 2<br />");
            }
    
            public static function test_func_3()
            {
                $c = new Sample_class_1();
                $c->test_func_1("func 3<br />");
            }
        }
    }
    
    // Now entering the root namespace...
    //  (You only need to do this if you've already used a different
    //   namespace in the same file)
    namespace
    {
        // Directly addressing a class
        $c = new sample\Sample_class_1();
        $c->test_func_1("Hello world<br />");
    
        // Directly addressing a class's static methods
        sample\Sample_class_2::test_func_2();
    
        // Importing a class into the current namespace
        use sample\Sample_class_2;
        sample\Sample_class_2::test_func_3();
    }
    
    // Now entering yet another namespace
    namespace sample2
    {
        // Directly addressing a class
        $c = new sample\Sample_class_1();
        $c->test_func_1("Hello world<br />");
    
        // Directly addressing a class's static methods
        sample\Sample_class_2::test_func_2();
    
        // Importing a class into the current namespace
        use sample\Sample_class_2;
        sample\Sample_class_2::test_func_3();
    }
    

    如果你在另一个文件里,你不需要打电话 namespace { 输入根命名空间。所以假设下面的代码是另一个文件“ns2.php”,而原始代码是“ns1.php”:

    // Include the other file
    include("ns1.php");
    
    // No "namespace" directive was used, so we're in the root namespace.
    
    // Directly addressing a class
    $c = new sample\Sample_class_1();
    $c->test_func_1("Hello world<br />");
    
    // Directly addressing a class's static methods
    sample\Sample_class_2::test_func_2();
    
    // Importing a class into the current namespace
    use sample\Sample_class_2;
    sample\Sample_class_2::test_func_3();
    
    推荐文章