0

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.

Dennis
  • 909
  • 4
  • 13
  • 30

1 Answers1

0

Although I don't recommend such a code as it is really hard to follow and understand, you can use the ReflectionClass to accomplish it:

class Test {
    private $foo;
    public function __construct($value){ 
        $this->foo = $value;
    }

    public function Bar(){ echo $this->foo; }
}

$string = "Something_Test";
$c = (new ReflectionClass(current(array_slice(explode('_', $string), 1 ,1))))->newInstanceArgs(["Some test text"]);
$c->Bar();
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
  • 1
    Great! I agree it's not the most readable code, which is a valid concern, but it's some pretty simple in terms of understanding reflection. It's a narrow usecase as well (basically a well hidden piece of code that does some class instantiation around a specific library to make the usage of that library a lot cleaner). It got commented up like a beast and is working - and I learned how php does reflection as well. Thanks! – Dennis Sep 27 '16 at 11:28