b. e. hollenbeck
b. e. hollenbeck

Reputation: 6573

Return an interface in PHP?

Is it possible to return an interface from a function? Example:

interface DBInterface {
  public function getDB();
  [...]
}

class Bar {

  public function defineDBObject($name){
    return DBInterface;
  }
}

I doubt it, but I have a client who likes to write involved spec docs that are calling for it. I want to make sure that it is, in fact, impossible.

Upvotes: 0

Views: 1420

Answers (3)

Champo
Champo

Reputation: 3419

You can return a ReflectionClass instance that represents the interface. Returning the interface directly is not possible.

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 60007

You cannot return an interface. You can only return an object. The object that you return can implement a particular interface - hence having those methods implemented.

It is a mechanism that is borrowed from Java to get over the diamond problem.

Upvotes: 1

rid
rid

Reputation: 63472

You can't. You can only return objects or primitives. Classes and interfaces are not objects in PHP.

Upvotes: 3

Related Questions