2012-08-26 50 views
6

我想在一些类和接口的php中使用名称空间。PHP命名空间和接口

看来我必须为接口和使用的具体类型提供一个使用语句。这有没有可靠的使用接口的目的?

所以我可能有

//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 
{} 

心不是接口的整点,这样的具体类型是可以互换的 - 这无疑违背了这一点。除非我没有正确地做某件事

回答

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); 
+0

因此,而不是使用'使用命名空间'只是使用类的完整路径呢? –

+1

不一定,您也可以将该类导入当前名称空间。这只是一个风格问题。 – Niko

+0

是的,我只是想,因为即时通讯使用接口,我想命名空间是接口 - 但实际上反射没有任何意义。更好的选择是使用依赖注入我想,并且从不实例化一个可以互换的类? –