PHP5和命名空间?

3

我经常使用PHP,但我从来没有真正理解PHP中的命名空间方法。有人可以帮我吗?我在php.net网站上阅读过它,但是它的解释不够好,我找不到相关示例。

我想知道如何在示例版本中编写代码。

  • 命名空间:sample
    • 类:sample_class_1
      • 函数:test_func_1
    • 类:sample_class_2
      • 函数:test_func_2
      • 函数:test_func_3
1个回答

4
像这样吗?
<?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();

好的,那么我需要在使用命名空间中的项目之前使用 "namespace" 吗? - ParisNakitaKejser
我之所以问是因为我想在需要使用这个命名空间作为框架时调用现有的类。 :) - ParisNakitaKejser
1
它的工作方式是,每个类(和函数、变量)都存在于命名空间中。如果您不使用“namespace”关键字,则假定您在根命名空间中。如果您想要使用来自不同命名空间的项目(例如,在“sample_2”或根中使用“sample”的类),则必须通过其完整名称(例如sample\Sample_class_1)或将其导入到当前命名空间中(使用use "sample\Sample_class_1";)。 - Michael Clerx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接