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
A namespace is a hierarchically labeled code block holding a regular PHP code. A namespace can contain valid PHP code. Namespace affects following types of code: classes (including abstracts and traits), interfaces, functions, and constants. Namespaces are declared using the namespace keyword.
Namespace is to avoid class name collisions, so you can have two same class names under two different namespaces. Use is just like PHP include. Please sign in or create an account to participate in this conversation.
Interface NamespaceAn interface that contains information about a namespace. Namespaces are accessed from a StartElement.
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With