An interface specifies what methods a class must implement, so that anything using that class that expects it to adhere to that interface will work.
eg: I expect any $database to have ->doQuery(), so any class I assign to the database interface should implement the databaseInterface interface which forces implementation of a doQuery method.
<?php
interface dbInterface {
public function doQuery();
}
class myDB implements dbInterface {
public function doQuery() {
}
}
$myDBObj = new myDB()->doQuery();
?>
An abstract class is similar except that some methods can be predefined. Ones listed as abstract will have to be defined as if the abstract class were an interface.
eg. I expect my $person to be able to ->doWalk(), most people walk fine with two feet, but some people have to hop along :(
<?php
interface PersonInterface() {
public function doWalk($place);
public function doAge();
}
abstract class AveragePerson implements PersonInterface() {
private $_age = 0;
public function doAge() {
$this->_age = $this->_age+1;
}
public function doWalk($place) {
echo "I am going to walk to $place".PHP_EOL;
}
abstract function talk($say);
}
class Joe extends AveragePerson {
public function talk($say) {
echo "In an Austrailian accent, Joe says: $say".PHP_EOL;
}
}
class Bob extends AveragePerson {
public function talk($say) {
echo "In a Canadian accent, Bob says: $say".PHP_EOL;
}
public function doWalk($place) {
echo "Bob only has one leg and has to hop to $place".PHP_EOL;
}
}
$people[] = new Bob();
$people[] = new Joe();
foreach ($people as $person) {
$person->doWalk('over there');
$person->talk('PHP rules');
}
?>