首页 > 解决方案 > PHP:通过对象属性值实例化类

问题描述

有没有办法使用对象属性的值来实例化一个新的类实例?

$arg = 'hello';
$class = $foo->bar;
$instance = new $class($arg);

这很好用,但我想跳过第二行,做一些类似的事情:

$instance = new {$foo->bar}($arg);

标签: php

解决方案


在 PHP 5.0.4+ 中这很好用:

$instance = new $foo->bar($arg);

完整示例:

<?php
$foo = new foo();
$arg = 'hello';
$class = $foo->bar;
$instance = new $class($arg);
$instance = new $foo->bar($arg); // your requested shorthand

class foo {
    public $bar = 'bar';
}

class bar {
    public function __construct($arg) {
        echo $arg;
    }
}

请参阅此工作示例


推荐阅读