I knew that I can use variable variables instead of reflection in PHP but I have never gone that way because my OOP background stated that this is not a clean way. Recently I made a test using both methods and the results made me rethink it.
Using variable variables is really less time consuming (almost 50%). My considerations now is how stable is this way. Is this behavior something that is in PHP and is not going to change? Sharing your opinions about that, tell me the disadvantages / advantages each way you think has. Thank you in advance for your responses.
<?php
// A simple test object
class testObj
{
private $id;
public function getId()
{
return $this->id;
}
public function setId($newId)
{
$this->id = $newId;
}
}
//Variable variables way
$startTime1 = microtime(true);
$a = "testObj";
$method = "setId";
$test1 = new $a;
$test1->$method(33);
$endTime1 = microtime(true);
echo "Variable variables way: ".(number_format($endTime1 - $startTime1,10))."<br/>";
var_dump($test1);
echo "<br/><br/>";
// Reflection way
$startTime2 = microtime(true);
$a = "testObj";
$method = "setId";
$reflectionClass = new ReflectionClass($a);
$test2 = $reflectionClass->newInstance();
$reflectionMethod = $reflectionClass->getMethod($method);
$reflectionMethod->invoke($test2,33);
$endTime2 = microtime(true);
echo "Reflection way: ".(number_format($endTime2 - $startTime2,10))."<br/>";
var_dump($test2);
?>