6

我正在尝试在 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
{}

不是接口的全部意义在于具体类型是可互换的 - 这肯定与此相反。除非我没有正确地做某事

4

1 回答 1

5

具体的实现是可以互换的,但是你需要在某个地方指定你想使用的实现,对吧?

// 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);
于 2012-08-26T19:21:59.610 回答