note 125484 added to class.reflectionmethod

From: Date: Mon, 02 Nov 2020 22:15:21 +0000
Subject: note 125484 added to class.reflectionmethod
Groups: php.notes 
Request: Send a blank email to php-notes+get-215781@lists.php.net to get a copy of this message
We can make a "Automatic dependenci injector" in classes when her constructors depends other classes (with type hint). <?php class Dependence1 { function foo() { echo "foo"; } } class Dependence2 { function foo2() { echo "foo2"; } } final class myClass { private $dep1; private $dep2; public function __construct( Dependence1 $dependence1, Dependence2 $dependence2 ) { $this->dep1 = $dependence1; $this->dep2 = $dependence2; } } // Automatic dependence injection (CLASSES) $constructor = new ReflectionMethod(myClass::class, '__construct'); $parameters = $constructor->getParameters(); $dependences = []; foreach ($parameters as $parameter) { $dependenceClass = (string) $parameter->getType(); $dependences[] = new $dependenceClass(); } $instance = new myClass(...$dependences); var_dump($instance); ?> Results in: object(myClass)#6 (2) { ["dep1":"myClass":private]=> object(Dependence1)#4 (0) { } ["dep2":"myClass":private]=> object(Dependence2)#5 (0) { } } ---- Server IP: 45.112.84.4 Probable Submitter: 185.85.3.174 (proxied: 179.96.134.88) ---- Manual Page -- http://php.net/manual/en/class.reflectionmethod.php Edit -- https://master.php.net/note/edit/125484 Del: integrated -- https://master.php.net/note/delete/125484/integrated Del: useless -- https://master.php.net/note/delete/125484/useless Del: bad code -- https://master.php.net/note/delete/125484/bad+code Del: spam -- https://master.php.net/note/delete/125484/spam Del: non-english -- https://master.php.net/note/delete/125484/non-english Del: in docs -- https://master.php.net/note/delete/125484/in+docs Del: other reasons-- https://master.php.net/note/delete/125484 Reject -- https://master.php.net/note/reject/125484 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#215781) next »