Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Namespaces and interfaces

Tags:

namespaces

php

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

like image 869
Marty Wallace Avatar asked Aug 26 '12 19:08

Marty Wallace


People also ask

What is a PHP namespace?

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.

What is the difference between namespace and use in PHP?

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.

What is Interface namespace?

Interface NamespaceAn interface that contains information about a namespace. Namespaces are accessed from a StartElement.

Does PHP support namespace?

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.


1 Answers

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);
like image 57
Niko Avatar answered Sep 23 '22 19:09

Niko