Can a class extend both a class and implement an Interface

PhpPhp Parse-Error

Php Problem Overview


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

Php Solutions


Solution 1 - Php

Try it the other way around:

class database extends mysqli implements databaseInterface { ...}

This should work.

Solution 2 - Php

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.

Solution 3 - Php

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

public class MyClass extends BaseClass implements myInterface1, myInterface2, myInterface3{ 

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPim JagerView Question on Stackoverflow
Solution 1 - PhpSimon LehmannView Answer on Stackoverflow
Solution 2 - PhpMichał NiedźwiedzkiView Answer on Stackoverflow
Solution 3 - PhpnullpointerView Answer on Stackoverflow