开发者

php5 and namespace?

I work a lot in PHP but I never really understand the namespace method in PHP. Can somebody help me here? I have read on php.net's website its not explained good enough, and I can't find examples on it.

I need to know how I can make code in sampl开发者_如何学JAVAe version.

  • namespace: sample
    • class: sample_class_1
      • function: test_func_1
    • class: sample_class_2
      • function: test_func_2
      • function: test_func_3


Like this?

<?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();
}

If you're in another file you don't need to call namespace { to enter the root namespace. So imagine the code below is another file "ns2.php" while the original code was in "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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜