StackOverflowNewbie
StackOverflowNewbie

Reputation: 40653

PHP: multiple namespace in same class?

I'm building a class that interacts with an API. Say the API has a "get_something" method for "foo" objects and "bar" objects. I want my class to expose a "get_something" method, but be able to distinguish if it's for "foo" or for "bar."

What's a good solution for me? Can I create a class that has multiple name spaces? Would that be a good idea?

Maybe I should have nested classes?

Upvotes: 0

Views: 808

Answers (2)

galchen
galchen

Reputation: 5290

you should look at namespaces as packages in java. a class belongs to 1 package only

what you can do though is have

namespace A_NS;
class A { ...}

namespace B_NS;
class A extends \A_NS\A {};

in that case class A will exist under namespace A_NS, and another class A' will exist under B_NS, which will extend class \NS_A\A;

you could check an object's class, or implement some identifier inside to distinguish.

overall, i would recommend that the design of your system will treat each class as if it belongs to 1 namespace only.

Upvotes: 1

Mike Purcell
Mike Purcell

Reputation: 19999

Two ways to do this, you can use an interface (http://us3.php.net/interface), which ensures that classes implementing the interface will have specified methods. Or create a parent class with abstract method (http://us3.php.net/abstract) get_something which will force any child classes to also have the class. Then you should be able to do a get_class($object) to determine which class was instantiated.

Upvotes: 0

Related Questions