2012-08-26 6 views
6

일부 클래스 및 인터페이스와 함께 PHP에서 네임 스페이스를 사용하려고합니다.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 
{} 

밤은 인터페이스의 요점이있을 수 있습니다. 내가 올바르게 뭔가를하지 않는 한

답변

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

대신 'use namespace'를 사용하는 대신 클래스의 전체 경로를 사용 하시겠습니까? –

+1

해당 클래스를 현재 네임 스페이스로 가져올 필요는 없습니다. 그것은 스타일의 문제 일뿐입니다. – Niko

+0

네, 저는 인터페이스를 사용하기 때문에 네임 스페이스가 인터페이스가되기를 바랄뿐입니다.하지만 실제로 반사에 대해서는 의미가 없습니다. 더 나은 옵션은 의존성 주입을 사용하는 것이고, 상호 교환 할 수있는 클래스를 인스턴스화하지 않을 것이라고 ?? –