Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php5 and namespace?

Tags:

namespaces

php

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 sample version.

  • namespace: sample
    • class: sample_class_1
      • function: test_func_1
    • class: sample_class_2
      • function: test_func_2
      • function: test_func_3
like image 623
ParisNakitaKejser Avatar asked Jul 27 '26 08:07

ParisNakitaKejser


1 Answers

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();
like image 176
Michael Clerx Avatar answered Jul 29 '26 21:07

Michael Clerx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!