Skip to content

Instantly share code, notes, and snippets.

@Pictor13
Forked from MarkBaker/anonymousFactory.php
Last active November 10, 2024 00:08
Show Gist options
  • Save Pictor13/faaa312d5e89433e30920805868f0a7e to your computer and use it in GitHub Desktop.
Save Pictor13/faaa312d5e89433e30920805868f0a7e to your computer and use it in GitHub Desktop.
Dynamic Instantiation of a class with optional Traits
<?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();
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