Is there are any native PHP function equivalent of the following:
function newObject($object) {
$class = get_class($object);
return new $class;
}
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.
function makeInstance($str){ return new $str; } and calling it like return makeInstance(get_class($x)), but that might just count as taking the longer route. @OP should stick to their implementation, as a function just for this purpose seems like an unlikely addition to the language,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);
get name of class object belongs to)