Home >Backend Development >PHP Tutorial >Problems with the use of namespace and use (detailed examples are attached)

Problems with the use of namespace and use (detailed examples are attached)

WBOY
WBOYOriginal
2016-09-08 08:43:501020browse

There are two php files in the same directory

Question:
How do I call the static methods of class a and class b in index.php respectively in class c in indexb.php?
How to fill in namespace and use?
File 1: index.php

<code>namespace {
    use 
   class a{
    static public function speak($a)
        {
            echo $a;
        }
   }

}
namespace {
use
    class a{
    static public function speak($a)
        {
            echo $a.$a;
        }
   }

}
</code>

File 2: indexb.php

<code>namespace Php {
    class c
    {
       
    }
}</code>

Reply content:

There are two php files in the same directory

Question:
How do I call the static methods of class a and class b in index.php respectively in class c in indexb.php?
How to fill in namespace and use?
File 1: index.php

<code>namespace {
    use 
   class a{
    static public function speak($a)
        {
            echo $a;
        }
   }

}
namespace {
use
    class a{
    static public function speak($a)
        {
            echo $a.$a;
        }
   }

}
</code>

File 2: indexb.php

<code>namespace Php {
    class c
    {
       
    }
}</code>

File index.php:

<code><?php
namespace A{
   class A{
       static public function speak($a)
       {
           echo $a;
       }
   }

}
namespace  B{
    class B{
        static public function speak($a)
        {
            echo $a;
        }
    }

}</code>

File indexb.php

<code><?php
namespace PHP{
    use A\A;
    use B\B;
    class C{
        public static function test(){
            include "index.php";
            A::speak("I am A!");
            B::speak("I am B!");
        }
    }
    //测试
    \PHP\C::test();
}</code>

Run indexb.php and the result is I am A! I am B!

Is this the result you want?

index.php

<code><?php

namespace test{

class a
{
    static public function speak($a)
    {
        echo $a;
    }
}
}

namespace test2{

class b 
{
    static public function speak($a)
    {
        echo $a.$a;
    }
}
}</code>

indexb.php

<code><?php

namespace testt{

include 'index.php';
use test\a;
use test2\b;

class c
{
    public $a;
    public function speak()
    {
//        var_dump(new a);
//        \test\a::speak($this->a);
        a::speak($this->a);
//        \test2\b::speak($this->a);
        b::speak($this->a);
    }
}

$c = new \testt\c();
$c->a = 'zhansan';
$c->speak();
}</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn