Implement an 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";
}
?>
Try it Yourself »
The implements
keyword is used to declare that a class must have the methods described in the specified interface. This is called polymorphism. Polymorphism makes it easy to use a variety of different objects in the same way.
The interface
keyword
The else
keyword
Read more about objects, classes and interfaces in our PHP OOP Tutorial.
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!