diff --git a/language/oop5/interfaces.xml b/language/oop5/interfaces.xml index c38e0cab78..4ddfdc59b6 100644 --- a/language/oop5/interfaces.xml +++ b/language/oop5/interfaces.xml @@ -5,7 +5,8 @@ Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are - implemented. + implemented. Interfaces share a namespace with classes and traits, so they may + not use the same name. Interfaces are defined in the same way as a class, but with the interface @@ -16,14 +17,34 @@ All methods declared in an interface must be public; this is the nature of an interface. - + + In practice, interfaces serve two complementary purposes: + + + + To allow developers to create objects of different classes that may be used interchangeably + because they implement the same interface or interfaces. A common example is multiple database access services, + multiple payment gateways, or different caching strategies. Different implementations may + be swapped out without requiring any changes to the code that uses them. + + + To allow a function or method to accept and operate on a parameter that conforms to an + interface, while not caring what else the object may do or how it is implemented. These interfaces + are often named like Iterable, Cacheable, Renderable, + or so on to describe the significance of the behavior. + + + + Interfaces may define + magic methods to require implementing classes to + implement those methods. + - It is possible to declare - magic methods such as the - constructor - in an interface, which can be useful in some contexts, - e.g. for use by factories. + Although they are supported, including constructors + in interfaces is strongly discouraged. Doing so significantly reduces the flexibility of the object implementing the + interface. Additionally, constructors are not enforced by inheritance rules, which can cause inconsistent + and unexpected behavior. @@ -41,6 +62,14 @@ same name, only if the method declaration in both interfaces is identical. + + + A class that implements an interface may use a different name for its parameters than + the interface. However, as of PHP 8.0 the language supports named arguments, which means + callers may rely on the parameter name in the interface. For that reason, it is strongly + recommended that developers use the same parameter names as the interface being implemented. + + Interfaces can be extended like classes using the extends @@ -49,8 +78,8 @@ - The class implementing the interface must declare a method which has a - compatible signature. + The class implementing the interface must declare all methods in the interface + with a compatible signature. @@ -71,8 +100,8 @@ +]]> + + + + Interfaces with abstract classes + + +]]> + + + + Extending and implementing simultaneously + + ]]>