Created
March 8, 2021 12:24
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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