简体   繁体   中英

PHP multiple classes implementing same interface

If I have an interface in PHP, say

interface AuthenticationInterface {
}

and two classes which implement the interface, for example

class ApiKey implements AuthenticationInterface {
}

class AuthToken implements AuthenticationInterface {
}

How is it determined which of these classes is used when a new AuthenticationInterface in instantiated?

Interfaces are used to define a structure(architecture) for classes that inherit it.

An interface is a contract specifying a set of methods, fields and properties which will be available on any implementing object

I think you were interested in the class factory design pattern. Read more about it here: php design patterns

Interface can't be instantiated. You can create object of class.

If your object was instantiated for you somewhere upstream and all you know is that it implements your AuthenticationInterface interface(so you know it can be one of a small number of classes...2 in your case), you can tell which class your object is by using "instanceof"

if ($your_object instanceof ApiKey)
{
    echo 'object class is ApiKey';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM