Created
August 15, 2022 07:46
-
-
Save alexander-zierhut/fbbcffcef3963700d036b5b1592cf874 to your computer and use it in GitHub Desktop.
Example of custumized inheritance based on the magic method __call
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 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