I'm trying to do a bit of php magic in one line with instantiating a class, but it seems the parser wont allow me. Example:
class Test{
private $foo;
public function __construct($value){
$this->foo = $value;
}
public function Bar(){ echo $this->foo; }
}
This can obviously be called like this:
$c = new Test("Some text");
$c->Bar(); // "Some text"
Now I want to instantiate this from some interesting string manipulation:
$string = "Something_Test";
$s = current(array_slice(explode('_', $string), 1 ,1)); // This gives me $s = "Test";
now I can instantiate it fine using:
$c = new $s("Some test text");
$c->Bar(); // "Someme test text"
But, I'm curious as why I cannot one-line this (or if there is a clever way), such that this would work:
$c = new $current(array_slice(explode('_', $string), 1 ,1))("Some test text"); //Doesn't work
I've tried using a variable variable as well:
$c = new $$current(array_slice(explode('_', $string), 1 ,1))("Some test text"); //Doesn't work
And I've tried to encapsulate it in some parenthesis' as well to no avail. I know the use case might seem odd, but it's intriguing to me to get to work and actually use some of the dynamic typing magic in php.
tl;dr: I want to imediately use the string return value to instantiate a class.