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

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

同级目录下有两个php文件

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

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

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

}

文件二:indexb.php

namespace Php {
    class c
    {
       
    }
}

是不是你想要的结果?

index.php

<?php

namespace test{

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

namespace test2{

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

indexb.php

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

文件index.php:

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

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

}

文件indexb.php

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

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

【热门文章】
【热门文章】