-
-
Save Pictor13/faaa312d5e89433e30920805868f0a7e to your computer and use it in GitHub Desktop.
Dynamic Instantiation of a class with optional Traits
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
<?php | |
class AnonymousClassBuilder { | |
private string $className; | |
private array $traits; | |
public function __construct(string $className) { | |
$this->className = $className; | |
} | |
public function withTraits(...$traits): static { | |
$this->traits = $traits; | |
return $this; | |
} | |
public function create(...$args): object { | |
$eval = "new class(...\$args) extends $this->className {" . PHP_EOL; | |
foreach($this->traits as $trait) { | |
$eval .= "use $trait;" . PHP_EOL; | |
} | |
$eval .= '}'; | |
return eval("return $eval;"); | |
} | |
} | |
class baseClass { | |
protected $a; | |
protected $b; | |
public function __construct($a, $b = null) { | |
$this->a = $a; | |
$this->b = $b; | |
} | |
public function sayWhat() { | |
echo $this->a, $this->b, PHP_EOL; | |
} | |
} | |
trait SayAB { | |
private $separator = ' '; | |
public function sayAB() { | |
echo $this->a, $this->separator, $this->b, PHP_EOL; | |
} | |
} | |
trait SayBA { | |
private $separator = ' '; | |
public function sayBA() { | |
echo $this->b, $this->separator, $this->a, PHP_EOL; | |
} | |
} | |
$anonBase = (new AnonymousClassBuilder('baseClass')) | |
->withTraits('SayAB', 'SayBA') | |
->create('hello', 'world'); | |
$anonBase->sayWhat(); | |
$anonBase->sayAB(); | |
$anonBase->sayBA(); |
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
A really hacky method of adding Traits to a class on instantiation, but creating an anonymous class as a wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment