在 php 中动态 class 创建

Dynamic class creation in php

我想通过实例化 class 在一行中做一些 php 魔术,但似乎解析器不允许我这样做。示例:

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

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

这显然可以这样调用:

$c = new Test("Some text");
$c->Bar(); // "Some text"

现在我想通过一些有趣的字符串操作来实例化它:

$string = "Something_Test";
$s = current(array_slice(explode('_', $string), 1 ,1)); // This gives me $s = "Test";

现在我可以很好地实例化它:

$c = new $s("Some test text");
$c->Bar(); // "Someme test text"

但是,我很好奇为什么我不能把它写成一行(或者如果有一个聪明的方法),这样就可以了:

$c = new $current(array_slice(explode('_', $string), 1 ,1))("Some test text"); //Doesn't work

我也试过使用可变变量:

$c = new $$current(array_slice(explode('_', $string), 1 ,1))("Some test text"); //Doesn't work

而且我也尝试将其封装在一些括号中,但无济于事。我知道这个用例可能看起来很奇怪,但开始工作并实际使用 php 中的一些动态类型魔法对我来说很有趣。

tl;dr:我想立即使用字符串 return 值来实例化 class.

虽然我不推荐这样的代码,因为它真的很难理解和理解,但你可以使用 ReflectionClass 来完成它:

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();