PHP implements 关键字
实例
实现一个接口:
<?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";
}
?>
定义和用法
implements
关键字用于声明一个类必须具有指定接口中描述的方法。 这称为多态性。 多态性使得以相同的方式使用各种不同的对象变得容易。
相关页面
interface
关键字
else
关键字
在我们的 PHP OOP 教程中了解有关对象、类和接口的更多信息。