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

报告相同问题?

悬赏问题

  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。