note 108466 added to reflectionclass.newinstancewithoutconstructor
| From: | me | Date: | Sat, 28 Apr 2012 06:51:09 +0000 |
| Subject: | note 108466 added to reflectionclass.newinstancewithoutconstructor | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-187389@lists.php.net to get a copy of this message | ||
This new Feature enables Annotation based Dependency Injection:
<?php
//dependency to inject
class dep {}
class a {
/**
* @inject
* @var dep
*/
protected $foo;
}
class b extends a {
/**
* @inject
* @var dep
*/
protected $bar;
public function __construct() {
echo "CONSTRUCTOR CALLED\n";
}
}
$ref = new ReflectionClass('b');
$inst = $ref->newInstanceWithoutConstructor();
$list = $ref->getProperties();
foreach($list as $prop){
/* @var $prop ReflectionProperty */
$prop->getDocComment(); //grep for @inject and the @vars class name
$prop->setAccessible(true);
$prop->setValue($inst, new dep());
}
if($const = $ref->getConstructor()) {
$constName = $const->getName();
$inst->{$constName}(); //use call_user_func_array($function, $param_arr); for arguments
}
print_r($inst);
print_r($inst->foo); //property still not accessable
The Output:
CONSTRUCTOR CALLED
b Object
(
[bar:protected] => dep Object
(
)
[foo:protected] => dep Object
(
)
)
PHP Fatal error: Cannot access protected property b::$foo in diTest.php on line 42
----
Server IP: 212.124.37.9
Probable Submitter: 92.203.39.26
----
Manual Page -- http://www.php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php
Edit -- https://master.php.net/note/edit/108466
Del: integrated -- https://master.php.net/note/delete/108466/integrated
Del: useless -- https://master.php.net/note/delete/108466/useless
Del: bad code -- https://master.php.net/note/delete/108466/bad+code
Del: spam -- https://master.php.net/note/delete/108466/spam
Del: non-english -- https://master.php.net/note/delete/108466/non-english
Del: in docs -- https://master.php.net/note/delete/108466/in+docs
Del: other reasons-- https://master.php.net/note/delete/108466
Reject -- https://master.php.net/note/reject/108466
Search -- https://master.php.net/manage/user-notes.php