Heim  >  Artikel  >  Backend-Entwicklung  >  namespace和use的使用问题(已附上详细例子)

namespace和use的使用问题(已附上详细例子)

WBOY
WBOYOriginal
2016-09-08 08:43:50942Durchsuche

同级目录下有两个php文件

问题:
我如何在indexb.php中的class c中分别调用index.php中class a 和 class b的静态方法?
namespace 和 use 该怎么填?
文件一: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>

文件二:indexb.php

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

回复内容:

同级目录下有两个php文件

问题:
我如何在indexb.php中的class c中分别调用index.php中class a 和 class b的静态方法?
namespace 和 use 该怎么填?
文件一: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>

文件二:indexb.php

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

文件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></code>

文件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></code>

运行indexb.php 结果I am A!I am B!

是不是你想要的结果?

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></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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn