The contract
An interface says what an object can do, not how it is built.
An interface lists public methods without bodies. A class writes implements and must implement them. This way a handler depends on Named, not on a specific User. A test can slip in another implementation.
An abstract class can hold part of the implementation. An interface cannot, apart from later additions with defaults, which are better kept out of a first lesson. For a contract like "can tell its name", an interface is enough.
One class can implement several interfaces. PHP allows a single parent class. Do not build a five-level tower for the sake of one field. Composition, an object inside an object, is often simpler than a subclass.
In the task the interface requires a name method. The class stores a string in the constructor and returns it from that method. The script prints the result. The contract is small, and that is its value: you can read it in full.
Practice
What implements promises
A class wrote implements Named. What must it do?
- Become final
- Implement the interface's methods
- Remove the constructor
- Extend three classes
The call
Which method is printed in this task? One word, without parentheses.
A name by contract
Describe an interface with a name method and a class User with the name Ann, and print the result of name.