Skip to content

Instantly share code, notes, and snippets.

@alexander-zierhut
Created August 15, 2022 07:46
Show Gist options
  • Save alexander-zierhut/fbbcffcef3963700d036b5b1592cf874 to your computer and use it in GitHub Desktop.
Save alexander-zierhut/fbbcffcef3963700d036b5b1592cf874 to your computer and use it in GitHub Desktop.
Example of custumized inheritance based on the magic method __call
<?php
class Factory {
protected $objectStorage = [];
public function assemble() {
foreach(func_get_args() as $className) {
$obj = new $className();
$this->objectStorage[] = [
"obj" => $obj,
"methods" => get_class_methods($obj)
];
}
}
public function __call($name, $arguments) {
foreach($this->objectStorage as $extension) {
if(in_array($name, $extension["methods"])) {
return $extension["obj"]->{$name}(...$arguments);
}
}
}
}
class Request extends Factory {
public function getPost($name) {
echo "getPost $name\n";
}
}
class Renderer {
public function render($text) {
echo "Render: $text\n";
}
}
class Hello {
public function world() {
echo "Hello World\n";
}
}
$req = new Request();
$req->assemble(
"Renderer",
"Hello"
);
$req->getPost("test");
$req->render("Example");
$req->world();
// Result:
// getPost test
// Render: Example
// Hello World
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment