Php check class implement interface

interface_exists

Returns true if the interface given by interface has been defined, false otherwise.

Examples

Example #1 interface_exists() example

// Check the interface exists before trying to use it
if ( interface_exists ( ‘MyInterface’ )) class MyClass implements MyInterface
// Methods
>
>

See Also

  • get_declared_interfaces() — Returns an array of all declared interfaces
  • class_implements() — Return the interfaces which are implemented by the given class or interface
  • class_exists() — Checks if the class has been defined
  • enum_exists() — Checks if the enum has been defined

User Contributed Notes 4 notes

As far as I remember interface_exists() was added in 5.0.2 . In 5.0.0 and 5.0.1 class_exists() used to return TRUE when asked for a existing interface. Starting 5.0.2 class_exists() doesn’t do that anymore.

Class and Interface share SAME namespace!

interface k <> // Fatal error: Cannot redeclare class k

A little note on namespaces that may be obvious to some, but was not obvious to me.

Although you can make the below statement when the statement is in the same namespace as the interface/class declaration MyInterface.
$foo instanceof MyInterface
?>

Making use of the interface_exists, or class_exists functions, you must enter the full namespaced interface name like so (even if the function call is from the same namespace.)
interface_exists ( __NAMESPACE__ . ‘\MyInterface’ , false );
?>

If you want to check for included interface and you already register spl autoloader — it will crash. Becassue autoloader trying to load `string` and he doesnt matter is it class or not.
Iv found several ways :
1 — unregister AL — -> check for Ifaces — -> register Autoloader

2 — $ifaces = array_flip(get_declared_interfaces());
if($ifaces[«MyIface»]) // empty // isset .

Interfaces are not bad, you can build correct geomentry of system , with validation by funcs / vars / const .
Also they are good to storage variables ROOT :: THEMES ; ROOT :: LOC ; ?> . Much faster then Define, but you cant put algorithms inside, only complite strings / __file__ / etc.

  • Classes/Object Functions
    • class_​alias
    • class_​exists
    • enum_​exists
    • get_​called_​class
    • get_​class_​methods
    • get_​class_​vars
    • get_​class
    • get_​declared_​classes
    • get_​declared_​interfaces
    • get_​declared_​traits
    • get_​mangled_​object_​vars
    • get_​object_​vars
    • get_​parent_​class
    • interface_​exists
    • is_​a
    • is_​subclass_​of
    • method_​exists
    • property_​exists
    • trait_​exists
    • _​_​autoload

    Источник

    ReflectionClass::implementsInterface

    Проверяет, реализует ли класс указанный интерфейс или нет.

    Список параметров

    Возвращаемые значения

    Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

    Ошибки

    ReflectionClass::implementsInterface() выбрасывает ReflectionException , если interface не является интерфейсом.

    Смотрите также

    • ReflectionClass::isInterface() — Проверяет, является ли класс интерфейсом
    • ReflectionClass::isSubclassOf() — Проверяет, является ли класс подклассом
    • interface_exists() — Проверяет, определён ли интерфейс
    • Интерфейсы объектов

    User Contributed Notes 3 notes

    Note that this method also returns true when the thing you’re reflecting is the interface you’re checking for:

    $reflect = new ReflectionClass ( ‘MyInterface’ );
    var_dump ( $reflect -> implementsInterface ( ‘MyInterface’ )); // bool(true)
    ?>

    interface Factory
    public function sayHello();
    >

    class ParentClass implements Factory
    public function sayHello()
    echo «hello\n»;
    >
    >

    class ChildrenClass extends ParentClass

    $reflect = new ReflectionClass(‘ParentClass’);
    var_dump($reflect->implementsInterface(‘Factory’));

    $second_ref = new ReflectionClass(‘ChildrenClass’);
    var_dump($second_ref->isSubclassOf(‘ParentClass’));

    $third_ref = new ReflectionClass(‘Factory’);
    var_dump($third_ref->isInterface());

    //can not be called as static
    var_dump(ReflectionClass::isInterface(‘Factory’));
    die;
    //#result
    bool(true)
    bool(true)
    bool(true)
    PHP Fatal error: Non-static method ReflectionClass::isInterface() cannot be called statically

    //checks that whether class Fruit implements interface apple or not

    class Fruit implements Apple

    $obj=new ReflectionClass(‘Fruit’);
    var_dump($obj->implementsInterface(‘Apple’)); //Here it will checks that whether class Fruit implements interface apple or not

    • ReflectionClass
      • _​_​construct
      • getAttributes
      • getConstant
      • getConstants
      • getConstructor
      • getDefaultProperties
      • getDocComment
      • getEndLine
      • getExtension
      • getExtensionName
      • getFileName
      • getInterfaceNames
      • getInterfaces
      • getMethod
      • getMethods
      • getModifiers
      • getName
      • getNamespaceName
      • getParentClass
      • getProperties
      • getProperty
      • getReflectionConstant
      • getReflectionConstants
      • getShortName
      • getStartLine
      • getStaticProperties
      • getStaticPropertyValue
      • getTraitAliases
      • getTraitNames
      • getTraits
      • hasConstant
      • hasMethod
      • hasProperty
      • implementsInterface
      • inNamespace
      • isAbstract
      • isAnonymous
      • isCloneable
      • isEnum
      • isFinal
      • isInstance
      • isInstantiable
      • isInterface
      • isInternal
      • isIterable
      • isIterateable
      • isReadOnly
      • isSubclassOf
      • isTrait
      • isUserDefined
      • newInstance
      • newInstanceArgs
      • newInstanceWithoutConstructor
      • setStaticPropertyValue
      • _​_​toString
      • export

      Источник

      class_implements

      This function returns an array with the names of the interfaces that the given object_or_class and its parents implement.

      Parameters

      An object (class instance) or a string (class or interface name).

      Whether to autoload if not already loaded.

      Return Values

      An array on success, or false when the given class doesn’t exist.

      Examples

      Example #1 class_implements() example

      interface foo < >
      class bar implements foo <>

      print_r ( class_implements (new bar ));

      // you may also specify the parameter as a string
      print_r ( class_implements ( ‘bar’ ));

      // use autoloading to load the ‘not_loaded’ class
      print_r ( class_implements ( ‘not_loaded’ , true ));

      The above example will output something similar to:

      Array ( [foo] => foo ) Array ( [foo] => foo ) Array ( [interface_of_not_loaded] => interface_of_not_loaded )

      See Also

      • class_parents() — Return the parent classes of the given class
      • get_declared_interfaces() — Returns an array of all declared interfaces

      User Contributed Notes 4 notes

      Hint:
      in_array ( «your-interface» , class_implements ( $object_or_class_name ));
      ?>
      would check if ‘your-interface’ is ONE of the implemented interfaces.
      Note that you can use something similar to be sure the class only implements that, (whyever you would want that?)
      array( «your-interface» ) == class_implements ( $object_or_class_name );
      ?>

      I use the first technique to check if a module has the correct interface implemented, or else it throws an exception.

      Calling class_implements with a non-loadable class name or a non-object results in a warning:

      // Warning: class_implements(): Class abc does not exist and could not be loaded in /home/a.panek/Projects/sauce/lib/Sauce/functions.php on line 196

      $interfaces = class_implements ( ‘abc’ );
      ?>

      This is not documented and should just return FALSE as the documentation above says.

      Luckily, it prints out superinterfaces as well in reverse order so iterative searching works fine:

      interface InterfaceB extends InterfaceA

      class MyClass implements InterfaceB

      print_r ( class_implements (new MyClass ()));

      Array
      (
      [InterfaceB] => InterfaceB
      [InterfaceA] => InterfaceA
      )

      Источник

      How do I know if a class implements an interface?

      How to Speed up Your WordPress Website

      In PHP, we can implement one (or more) interface in a class.

       interface Authenticable < // métodos >interface Model < // métodos >class Person implements Authenticable, Model < // métodos >

      In the example above, Person implements Authenticable and Model .

      How can I make a check to see if a particular class implements an interface? For example, how do you know that a given instance of Person implements Authenticable ?

      Note : I always use versions of PHP 5.4 > =. So a more current form would be preferable for such an operation.

      2 answers

      interface Authenticable < // métodos >interface Model < // métodos >class Person implements Authenticable, Model < // métodos >$pessoa = new Person(); if ($pessoa instanceof Model) < echo "implementa Model"; >if ($pessoa instanceof Cloneable)

      It’s not what you want and in a few situations it’s useful (I think only if you’re doing some help), but if you prefer you can list everything :

      interface Authenticable < // métodos >interface Model < // métodos >class Person implements Authenticable, Model < // métodos >$pessoa = new Person(); print_r(class_implements($pessoa)); 

      To know which interfaces a class implements, simply use the SPL function class_implements ()

      array class_implements ( mixed $class [, bool $autoload = true ] ) 

      From PHP 5.1 you can set the class name to string:

      $rs = class_implements('Foo'); var_dump($rs); 

      We can use instanceof as a more practical medium, but we need to make sure that the instance is an interface, otherwise it may create an inconsistency by returning extended classes rather than interfaces. What’s more, with instanceof it is assumed that you already know the names of the interfaces. With class_implements() an array of names of the implemented objects is returned. It is most useful for when you do not know which objects are implemented.

      These are the objects we will use for testing:

      interface iFoo < >class Bar < >class Foo implements ifoo < >class Foo2 extends Bar

      Test with class_implements ()

      $rs = class_implements('Foo'); var_dump($rs); /* array(1) < ["iFoo"]=>string(4) "iFoo" > */ $rs = class_implements('Foo2'); var_dump($rs); /* Foo2 é uma instância de Bar, porém, não retorna ao invocar class_implements() por ser uma class e não uma interface. O resultado nesse caso é vazio. array(0) < >*/ 

      Test with instanceof

      O uso do 'instanceof' pode causar inconsistência. Veja o exemplo: $c = new Foo; if ($c instanceof iFoo) < echo 'yes'; >else < echo 'no'; >/* iFoo é uma interface. O retorno é 'yes'. */ $c = new Foo2; if ($c instanceof Bar) < echo 'yes'; >else < echo 'no'; >/* Bar() não é uma interface, mas ainda assim retorna 'yes' porque instanceof não distingue se o objeto é uma class ou uma interface. Isso é um exemplo de inconsistência. */ 

      It is good to make it clear that I do not mean that it is wrong to use instanceof for this purpose (within the context of the question), provided the caveats are observed.

      However, it is good to point out the inconsistency when indicating the use of instanceof for this purpose. For security, use whichever is more consistent, the class_implements() function.

      Reflection?

      I would not even want to comment on the use of Reflection because for static tasks there is no sense in using OOP classes.

      But if you already have an instance of ReflectionClass () , you can take advantage of it to get a list of the interfaces that the object implements:

      $rs = new ReflectionClass('Foo'); var_dump($rs->getInterfaces()); /* array(1) < ["iFoo"]=>object(ReflectionClass)#2 (1) < ["name"]=>string(4) "iFoo" > > */ 

      Note: The examples above show only how to abstract the data. I do not need to show how to use if else , in_array() and stuff like that to get the name of an object that might be present in the result. After all, anyone who is reading this should know how to use such basic things.

      Источник

      Читайте также:  Math random javascript диапазон
Оцените статью