[Switch] PHP implements multiple inheritance through interfaces. Although PHP classes are single-inherited, multiple inheritance can be implemented through other special methods, such as using interfaces, you only need to abstract the features of a class as an interface and implement the interface to make the object have multiple identities. in this way, you can simulate multiple inheritance. The following is an example of simulating multiple inheritance using interfaces. the source code is as follows: & lt ;?? Interface? U [to] PHP implements multiple inheritance through interfaces
Although PHP classes are single-inherited, multiple inheritance can be implemented in other special ways. for example, if you use interfaces to abstract the features of a class as interfaces, the interface is implemented to make the object have multiple parts, so that you can simulate multiple inheritance.
The following is an example of simulating multiple inheritance using interfaces. the source code is as follows:
-
- Interface? UserInterface {? // Define the User interface?
- ? Function? Getname ();?
- }?
- Interface? TeacherInterface {? // Teacher related interfaces?
- ? Function? GetLengthOfService ();?
- }?
- Class? User? Implements? UserInterface? {? // Implement the UserInterface interface?
- ? Private? $ Name? =? "Tom ";?
- ? Public? Function? GetName (){?
- ?? Return? $ This-> name ;?
- ?} ?
- }?
- Class? Teacher? Implements? TeacherInterface? {? // Implement the TeacherInterface interface?
- ? Private? $ LengthOfService? =? 5 ;? //? Working age? ?
- ? Public? Function? GetLengthOfService (){?
- ?? Return? $ This-> lengthOfService ;?
- ?} ?
- }?
- //? Inherits from the User class and implements the TeacherInterface interface .?
- Class? GraduateStudent? Extends? User? Implements? TeacherInterface? {?
- ? Private? $ Teacher ?; ?
- ? Public? Function? _ Construct (){?
- ?? $ This-> teacher? =? New? Teacher ();?? ?
- ?}? ?
- ? Public? Function? GetLengthOfService (){?
- ?? Return? $ This-> teacher-> getLengthOfService ();?
- ?} ?
- }?
- Class? Act {?
- ? // Note that the type prompt here is changed to the interface type?
- ? Public? Static? Function? GetUserName (UserInterface? $ _ User ){?
- ?? Echo? "Name? Is? "?.? $ _ User-> getName ()?. "
";?
- ?} ?
- ? // The type prompt here is changed to the TeacherInterface type .?
- ? Public? Static? Function ?? GetLengthOfService (TeacherInterface? $ _ Teacher ){?
- ?? Echo? "Age? Is? "?. $ _ Teacher-> getLengthOfService ()?. "
";?
- ?} ?
- }?
- $ GraduateStudent? =? New? GraduateStudent ();?
- Act: getUserName ($ graduateStudent );?
- Act: getLengthOfService ($ graduateStudent );?
- // The result is an object with multiple identities, as we need .?
- ?>?
The running result is as follows:
Name is tom
Age is 5