The feature illustrated below operates on PHP values, objects, or language metadata.
What Is interface_exists in PHP?
Checks whether an interface with the supplied name is defined; autoloading is enabled by default.
interface_exists(string $interface, bool $autoload = ...) : bool
Parameters:
$interface— Required. An interface identifier used for comparison.$autoload— Optional. The autoload argument used to configure this operation; its accepted values follow the declared PHP type.
Return type: bool. Autoloading may run when checking an interface name.
Example 1: Understanding the Basic Behavior
<?php
interface Exportable {}
var_dump(interface_exists(Exportable::class));
Output:
bool(true)
Explanation: Checks whether an interface with the supplied name is defined; autoloading is enabled by default.
Example 2: Testing Another Case
<?php
var_dump(interface_exists('NonExistentInterface', false));
Output:
bool(false)
Explanation: Autoloading may run when checking an interface name.
Practical Example: Applying the Operation
<?php
interface Sender { public function send(string $message): void; }
if (interface_exists(Sender::class)) { echo 'The contract is available'; }
Output:
The contract is available
Explanation: class_exists() checks classes, not interface declarations.
Important Behavior and Edge Cases
- Autoloading may run when checking an interface name.
- class_exists() checks classes, not interface declarations.
Comparison With Related Approaches
| Approach | When to Use It |
|---|---|
interface_exists | Checks whether an interface with the supplied name is defined; autoloading is enabled by default. |
class_exists() | interface_exists() tests an interface name; class_exists() tests class names and excludes interfaces. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Using class_exists() when the expected declaration is an interface. | Autoloading may run when checking an interface name. |
| Choosing class_exists() without checking whether it provides the same result. | interface_exists() tests an interface name; class_exists() tests class names and excludes interfaces. |
Key Takeaways
- Checks whether an interface with the supplied name is defined; autoloading is enabled by default.
- Autoloading may run when checking an interface name.
- class_exists() checks classes, not interface declarations.
The examples demonstrate where interface_exists fits within php programming. Verify the relevant preconditions whenever you adapt the code to real data.