brietsparks
brietsparks

Reputation: 5006

PHP create empty object using existing object of same class

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

Answers (2)

bishop
bishop

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);

See it live.

Upvotes: 1

GolezTrol
GolezTrol

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

Related Questions