Why do programmers use interfaces in PHP?
Think about how interfaces help different classes work together.
Interfaces define a set of methods that classes must implement. This ensures that different classes have the same method names and signatures, making code more predictable and easier to maintain.
What will be the output of this PHP code?
<?php interface Talker { public function talk(); } class Person implements Talker { public function talk() { return "Hello!"; } } $person = new Person(); echo $person->talk(); ?>
Check if the class implements all methods from the interface.
The class Person implements the Talker interface and defines the talk() method. When called, it returns "Hello!" which is printed.
What error will this PHP code produce?
<?php interface Flyer { public function fly(); } class Bird implements Flyer { // Missing fly() method } $bird = new Bird(); $bird->fly(); ?>
Check if the class implements all interface methods.
The Bird class claims to implement the Flyer interface but does not define the required fly() method. PHP throws a fatal error because the contract is broken.
Which of the following PHP code snippets correctly defines an interface and a class that implements it?
Remember interfaces only declare methods without bodies.
Option B correctly declares an interface with a method signature and a class that implements it with the method body. Option B tries to define a method body inside the interface, which is invalid. Option B is corrected to include the function keyword. Option B does not implement the interface.
Consider a PHP program that uses an interface Logger with a method log(). Two classes, FileLogger and DatabaseLogger, implement Logger differently. How does using the Logger interface improve the program?
Think about how interfaces let you swap implementations easily.
Using the Logger interface means the program can switch between FileLogger and DatabaseLogger without changing the code that uses the logger. This makes the code more flexible and easier to maintain.