1

I am writing a PHP interface and I am wondering whether I should have a namespace statement in that interface file.

So is it a good idea to have an interface within a namespace or should only the class implementing the interface be within a namespace? Or should they both have (different) namespaces?

Here is an example for an interface within a namespace:

<?php
namespace \Vendor\App\DatabaseAccess;

interface DatabaseAccessInterface
{
}

Here is an example for an implementation of that interface within the same namespace:

<?php
namespace \Vendor\App\DatabaseAccess;

class DatabaseAccess implements DatabaseAccessInterface
{
}

The interface and the class could be in the same namespace as in the examples or in different namespaces. Alternatively, the interface could leave out the namespace declaration alltogether. Which way is the most appropriate for code reusability and why?

Soong
  • 246
  • 2
  • 10
  • Can you elaborate your questions with some examples? – greut Aug 19 '15 at 10:11
  • 2
    Does the interface belong in a namespace? Use the same principles you would for a class - if it makes sense to use a namespace, use one. Generally the answer is yes (use a namespace), don't clutter the global namespace with your custom interfaces. – naththedeveloper Aug 19 '15 at 10:22
  • Yes, it should. So, .. do it! – sensorario Sep 04 '15 at 12:24

1 Answers1

2

nathanthedeveloper is correct in his comment that the answer is to use the same principles as for determining the class namespace. The reason for namespacing is to not clutter the global namespace and there is really no difference between classes and interfaces in that regard. So the answer is yes, interfaces should have a namespace and it should be the same as for the class because they both belong to the same logical place.

Soong
  • 246
  • 2
  • 10