I would like to be able to instantiate a class using a class name stored in another class's property, and I want to do this with one line of code, as in the comments in the code below (and it should work on at least one recent version of PHP 5). Is this possible?
<?php
class Foo {
public function doFoo() {
echo "foo
";
}
}
class Bar {
function __construct($className) {
$this->className = $className;
}
public function doBar() {
//INSTEAD OF THESE TWO LINES...
//$className = $this->className;
//$instance = new $className();
//I WOULD LIKE THIS (OR SOME OTHER) ONE-LINER TO WORK:
$instance = $this->className();
$instance->doFoo();
}
}
$bar = new Bar('Foo');
$bar->doBar();
EXPECTED OUTPUT:
foo