PHP interface Keyword

❮ PHP Keywords

Example

Create and 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 »

Definition and Usage

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.


Related Pages

The implements keyword


❮ PHP Keywords
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.