PHP is now no where treated as weak language, day after day and with every next release of php’s new version more of the robust features are being added. Now this time, i was going through the PHP’s RSS feeds and i realized that now reflection fuctionality is also supported by PHP v 5.1.3
It makes PHP more closer to its near competitor JAVA. Well a small code which shows how can we implement reflections in php is given below. It is little slow as compared to its alternative Switch-case statement but you get some neat coding and lesser LOC.
Reflections are always heavy for server according to some benchmarks, but it is always nicer to use reflections over messed up switch case statements. 😉
Code in Reflections:
[php]
function init($name,$init) {
if (count($init) == 0) {
return new $name();
} else {
$classObj = new ReflectionClass($name);
return $classObj->newInstanceArgs($init);
}
}
[/php]
Same Code using Switch-Case Statements:
[php]
function init($name,$init) {
switch(count($init)) {
case 0:
return new $name();
case 1:
return new $name($init[0]);
case 2:
return new $name($init[0],$init[1]);
case 3:
return new $name($init[0],$init[1],$init[2]);
case 4:
//etc…
}
}
[/php]
Cheers !!
Realin !