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";
}
?>
亲自试一试 »
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";
}
?>
定义和用法
interface
关键字用于创建接口。
接口是一种结构,它定义了必须存在于类中的方法列表。
接口是允许以相同方式使用许多不同类的好方法。
implements
关键字可用于使类使用接口。
相关页面
实现
关键字