doubei8541 2016-09-27 07:50
浏览 61
已采纳

php中的动态类创建

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.

  • 写回答

1条回答 默认 最新

  • duangang3832 2016-09-27 08:02
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效