Can a class extend both a class and implement an Interface

前端 未结 3 1258
执念已碎
执念已碎 2021-01-30 06:06

Can a class extend both an interface and another class in PHP?
Basically I want to do this:

interface databaseInterface{
 public function query($q);
 public         


        
相关标签:
3条回答
  • 2021-01-30 06:38

    yes, in fact if you want to implement multiple interfaces you can do like this:

    public class MyClass extends BaseClass implements myInterface1, myInterface2, myInterface3{ 
    
    }
    
    0 讨论(0)
  • 2021-01-30 06:39

    Yes it can. You just need to retain the correct order.

    class database extends mysqli implements databaseInterface { ... }
    

    Moreover, a class can implement more than one interface. Just separate 'em with commas.

    However, I feel obliged to warn you that extending mysqli class is incredibly bad idea. Inheritance per se is probably the most overrated and misused concept in object oriented programming.

    Instead I'd advise doing db-related stuff the mysqli way (or PDO way).

    Plus, a minor thing, but naming conventions do matter. Your class database seems more general then mysqli, therefore it suggests that the latter inherits from database and not the way around.

    0 讨论(0)
  • 2021-01-30 06:41

    Try it the other way around:

    class database extends mysqli implements databaseInterface { ...}
    

    This should work.

    0 讨论(0)
提交回复
热议问题