PHP Tutorials
PHP Forms
PHP Advanced
PHP OOP
Visual connectors allow you to specify which methods the class should use.
The interface makes it easy to use different classes in the same way. When one or more class uses the same visual connector, it is called a "polymorphism".
Interfaces are announced by the interface
keyword:
<?php
interface InterfaceName {
public function someMethod1();
public function someMethod2($name, $color);
public function
someMethod3() : string;
}
?>
Visible connector is similar to invisible classes. The differences between interfaces and abstract classes are:
In order to use the interface, the class must use the keyword of the implements
.
The communication class should use all the interface modes.
<?php
interface Animal {
public function makeSound();
}
class Cat implements Animal {
public function makeSound() {
echo "Meow";
}
}
$animal = new Cat();
$animal->makeSound();
?>
From the example above, let's say we'd like to write software that manages a group of animals. There are actions that every animal can do, but each animal does it in its own way.
Using meeting places, we can write code that can apply to all animals even if each animal behaves differently:
<?php
// Interface definition
interface Animal {
public
function makeSound();
}
// Class definitions
class Cat
implements Animal {
public function makeSound() {
echo " Meow ";
}
}
class Dog implements Animal {
public function makeSound()
{
echo " Bark ";
}
}
class Mouse implements Animal {
public function makeSound() {
echo " Squeak ";
}
}
// Create a list
of animals
$cat = new Cat();
$dog = new Dog();
$mouse = new
Mouse();
$animals = array($cat, $dog, $mouse);
// Tell the animals
to make a sound
foreach($animals as $animal) {
$animal->makeSound();
}
?>
Cat, Dog and Mouse all classes use the Visual Animal Connector, which means they can all make sound using the makeSound()
method. Because of this, we can get into every animal and tell them to make a noise even if we do not know what kind of animal they are.
Since the interface does not tell the classes how to use the method, each animal can make a sound in its own way.