原文地址:http://www.davegardner.me.uk/blog/2010/11/21/why-you-should-always-use-php-interfaces/
在这里只列出文章里面的代码
// our interface
interface userInterface {
public function isMember();
}
// our concrete user class
class user implements userInterface {
private $paidUntil;
public function __construct($paidUntil) {
$this->paidUntil = $paidUntil;
}
public function isMember() {
return $paidUntil > time();
}
}
// our proxy
class userProxy implements userInterface {
private $dao;
private $user;
private $userId;
public function __construct($dao, $userId) {
$this->dao = $dao;
// set user to NULL to indicate we haven't loaded yet
$this->user = NULL;
}
public function isMember() {
if ($this->user === NULL) {
$this->lazyLoad();
}
return $this->user->isMember();
}
private function lazyLoad() {
$this->user = $this->dao->getById($this->userId);
}
}
class inviteList {
public function add(userInterface $user) {
if (!$user->isMember()) {
throw new youMustPayException('You must be a member to get an invite.');
}
// do something else
}
}