Can a class extend both classes and implement an interface

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 function escape($s); //more methods } class database{ //extends both mysqli and implements databaseInterface //etc. } 

How to do this simply by doing:

 class database implements databaseInterface extends mysqli{ 

leads to a fatal error:

 Parse error: syntax error, unexpected T_EXTENDS, expecting '{' in * file * on line * line *
+79
php php-parse-error
Mar 16 '09 at 21:08
source share
3 answers

Try the opposite:

 class database extends mysqli implements databaseInterface { ...} 

That should work.

+134
Mar 16 '09 at 21:11
source share

Yes maybe. You just need to keep the correct order.

 class database extends mysqli implements databaseInterface { ... } 

In addition, a class can implement more than one interface. Just separate them with commas.

However, I feel obligated to warn you that extending the mysqli class is an incredibly bad idea . Inheritance as such is probably the most overrated and misused concept in object-oriented programming.

Instead, I would recommend using db-related things with mysqli (or PDO).

Plus, secondary, but naming conventions matter. Your database class seems more general than mysqli , so it assumes the latter inherits from database , and not vice versa.

+16
Mar 16 '09 at 21:14
source share

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

 public class MyClass extends BaseClass implements myInterface1, myInterface2, myInterface3{ } 
+3
Sep 12 '15 at 13:53 on
source share



All Articles