Skip to content

Instantly share code, notes, and snippets.

@M1ke
Created March 8, 2021 12:24
Show Gist options
  • Save M1ke/d2c0aabc4d9cd4d507b76ddc5b3f4d8d to your computer and use it in GitHub Desktop.
Save M1ke/d2c0aabc4d9cd4d507b76ddc5b3f4d8d to your computer and use it in GitHub Desktop.
Demonstrates the use of traits and interfaces to "mock" multiple inheritance in PHP
interface AsNumber {
public function asNumber(): int;
}
interface CanBeAdded {
public function add(AsNumber $b): int;
}
interface CanBeMultiplied {
public function multiply(AsNumber $b): int;
}
/** @psalm-require-implements AsNumber */
trait NumberAdd {
public function add(AsNumber $b): int{
return $this->asNumber() + $b->asNumber();
}
}
/** @psalm-require-implements AsNumber */
trait NumberMultiply {
public function multiply(AsNumber $b): int{
return $this->asNumber() * $b->asNumber();
}
}
class RandomNumber implements AsNumber, CanBeAdded {
use NumberAdd;
public function asNumber(): int{
return random_int(1, 10);
}
}
class FixedNumber implements AsNumber, CanBeMultiplied, CanBeAdded {
use NumberAdd;
use NumberMultiply;
/** @var int */
private $number;
public function __construct(int $number){
$this->number = $number;
}
public function asNumber(): int{
return $this->number;
}
}
$random = new RandomNumber;
$fixed = new FixedNumber(5);
echo $random->add($fixed)."\n";
echo $fixed->multiply($random);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment