Reputation: 5006
Is there are any native PHP function equivalent of the following:
function newObject($object) {
$class = get_class($object);
return new $class;
}
Upvotes: 2
Views: 232
Reputation: 39364
Single function, no. Idiomatic way, yes. Use ReflectionObject
:
class Foo {
}
$foo = new Foo();
$foo->bar = 'baz';
// this is the magic:
$new = (new ReflectionObject($foo))->newInstance();
var_dump($foo, $new);
Upvotes: 1
Reputation: 116100
I don't think there is.
And there is no shortcut either. new get_class($x);
tries to use the class get_class
, and new (get_class($x));
is syntactically incorrect, because the parentheses are not allowed. You can use a variable containing a class name, but you cannot use any string expression.
Upvotes: 1