PHP Namespaces and interfaces

namespaces, php

Solution

The concrete implementation IS interchangeable, but you need to specify somewhere which implementation you'd like to use, right?

// 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);

Problem

I am trying to use namespaces in php with some classes and interfaces. It appears that I must put a use statement for both the interface and the concrete type being used. This is kind of defeating the purpose of using interfaces surely? So i may have ``` //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 {} ``` Isnt the whole point of interfaces so that the concrete types are interchangeable - this goes against that surely. Unless i am not doing something correctly

Original source