Welcome to the Linux community forum and interact with 2 million technical staff. Use interfaces in php to implement multiple inheritance: we all know that classes in PHP are individually inherited, is there no way to implement multi-inheritance? The answer is no. we can implement multiple inheritance of classes in other special ways, such as using interfaces (interf
Welcome to the Linux community forum and interact with 2 million technical staff> use interfaces in php to implement multiple inheritance: we all know that classes in PHP are individually inherited, is there no way to implement multi-inheritance? The answer is no. we can implement multiple inheritance of classes in other special ways, such as using interfaces (interf
Welcome to the Linux community forum and interact with 2 million technicians>
Using Interfaces in php to implement multiple inheritance:
We all know that classes in PHP are single-inherited. Is there no way to implement multi-inheritance? The answer is no. we can implement multi-inheritance of classes in other special ways. For example, we can use interfaces to abstract the features of classes as interfaces, the interface is implemented to enable the object to have multiple identities, so that multiple inheritance can be simulated.
The following is an example of multi-inheritance Using Interfaces. The source code is as follows:
Interface UserInterface {// define the User interface
Function getname ();
}
Interface TeacherInterface {// teacher interface
Function getLengthOfService ();
}
Class User implements UserInterface {// implements the UserInterface Interface
Private $ name = "tom ";
Public function getName (){
Return $ this-> name;
}
}
Class Teacher implements TeacherInterface {// implement the TeacherInterface Interface
Private $ lengthOfService = 5; // length of service
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