PHP使用同一类的现有对象创建空对象


PHP create empty object using existing object of same class

是否有与以下内容等效的本地PHP函数:

function newObject($object) {
    $class = get_class($object);
    return new $class;
}

我认为没有.

也没有捷径可走。new get_class($x);尝试使用类get_class,而new (get_class($x));在语法上不正确,因为不允许使用括号。可以使用包含类名的变量,但不能使用任何字符串表达式。

单个函数,不。惯用方法,是。使用ReflectionObject:

class Foo {
}
$foo = new Foo();
$foo->bar = 'baz';
// this is the magic:
$new = (new ReflectionObject($foo))->newInstance();
var_dump($foo, $new);

现场观看。