Interfaces and Traits
Interface Shape
Different classes can share a method shape by implementing the same interface.
Interface Shape
interface_shape.php
<?php
interface Measurable
{
public function measure(): int;
}
class Rectangle implements Measurable
{
public function __construct(private int $width, private int $height)
{
}
public function measure(): int
{
return $this->width * $this->height;
}
}
$width = ;
$shape = new Rectangle($width, 3);
$area = $shape->measure();
echo "width=" . $width . "\n";
echo "area=" . $area . "\n";
<?php
interface Measurable
{
public function measure(): int;
}
class Rectangle implements Measurable
{
public function __construct(private int $width, private int $height)
{
}
public function measure(): int
{
return $this->width * $this->height;
}
}
$width = ;
$shape = new Rectangle($width, 3);
$area = $shape->measure();
echo "width=" . $width . "\n";
echo "area=" . $area . "\n";
<?php
interface Measurable
{
public function measure(): int;
}
class Rectangle implements Measurable
{
public function __construct(private int $width, private int $height)
{
}
public function measure(): int
{
return $this->width * $this->height;
}
}
$width = ;
$shape = new Rectangle($width, 3);
$area = $shape->measure();
echo "width=" . $width . "\n";
echo "area=" . $area . "\n";
shared shape
The caller only needs the methods promised by the interface.