Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a class extend both a class 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 would one do this, simply doing:

class database implements databaseInterface extends mysqli{  

results in a fatal error:

 Parse error: syntax error, unexpected T_EXTENDS, expecting '{' in *file* on line *line* 
like image 819
Pim Jager Avatar asked Mar 16 '09 21:03

Pim Jager


People also ask

Can a class extend a class and implement an interface?

A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.

Can you extend and implement an interface?

An interface can extend any number of interfaces. An interface can never implement any other interface.

Can a class extend an abstract class and implement an interface at the same time?

Yes, it is correct.

Can we use extends and implements together in PHP?

We use an interface by using the implements keyword. It's very similar to extending other classes, but only works for interfaces. The implements keyword also allows us to implement multiple interfaces, whereas extending in PHP only allows you to extend one class.


2 Answers

Try it the other way around:

class database extends mysqli implements databaseInterface { ...} 

This should work.

like image 87
Simon Lehmann Avatar answered Oct 04 '22 22:10

Simon Lehmann


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.

like image 37
Michał Niedźwiedzki Avatar answered Oct 04 '22 22:10

Michał Niedźwiedzki