PHP 8.5.0 Alpha 4 available for testing

Voting

: nine minus six?
(Example: nine)

The Note You're Voting On

jai at shaped dot ca
8 years ago
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() {
/* implementation details here */
}
}

$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() {
/* every person should walk, or attempt to */
public function doWalk($place);
/* every person should be able to age */
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;
}
/* every person talks differently! */
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');
}
?>

<< Back to user notes page

To Top