我试图在PHP中使用一些类和接口的命名空间.
看来我必须为接口和使用的具体类型设置一个use语句.这肯定会破坏使用接口的目的吗?
所以我可能有
//Interface
namespace App\MyNamesapce;
interface MyInterface
{}
//Concrete Implementation
namespace App\MyNamesapce;
class MyConcreteClass implements MyInterface
{}
//Client
namespace App;
use App\MyNamespace\MyInterface // i cannot do this!!!!
use App\MyNamespace\MyConcreteClass // i must do this!
class MyClient
{}
Run Code Online (Sandbox Code Playgroud)
不是接口的全部要点,以便具体类型可以互换 - 这肯定与此相反.除非我没有正确地做某事
具体实现是可以互换的,但是你需要在某个地方指定你想要使用的实现,对吧?
// Use the concrete implementation to create an instance
use \App\MyNamespace\MyConcreteClass;
$obj = MyConcreteClass();
// or do this (without importing the class this time):
$obj = \App\MyNamespace\MyConcreteClass2(); // <-- different concrete class!
class Foo {
// Use the interface for type-hinting (i.e. any object that implements
// the interface = every concrete class is okay)
public function doSomething(\App\MyNamespace\MyInterface $p) {
// Now it's safe to invoke methods that the interface defines on $p
}
}
$bar = new Foo();
$bar->doSomething($obj);
Run Code Online (Sandbox Code Playgroud)