PHP interface 关键字
示例
创建并实现接口
<?php
interface Machine {
public function activate();
public function deactivate();
public function isActive();
}
class Kettle implements Machine {
private $isOn = false;
public function activate() {
$this->isOn = true;
}
public function deactivate() {
$this->isOn = false;
}
public function isActive() {
return $this->isOn;
}
}
$machine = new Kettle();
$machine->activate();
if($machine->isActive()) {
echo "The machine is on";
} else {
echo "The machine is off";
}
echo "<br>";
$machine->deactivate();
if($machine->isActive()) {
echo "The machine is on";
} else {
echo "The machine is off";
}
?>
自己动手试一试 »
定义和用法
The interface
keyword is used to create interfaces.
An interface is a structure which defines a list of methods that must exist in a class.
Interfaces are a good way to allow many different classes to be used in the same way.
The implements
keyword can be used to make a class use an interface.
相关页面
The implements
keyword
❮ PHP 关键字