2

Is there are any native PHP function equivalent of the following:

function newObject($object) {
    $class = get_class($object);
    return new $class;
}
4
  • 1
    Well, what do you know? (first result for get name of class object belongs to) Commented Nov 25, 2015 at 20:15
  • @DJDavid98 not quite. That returns name of class, not actual object. Said function is used in the example Commented Nov 25, 2015 at 20:16
  • Nevermind, I didn't notice you needed a native function. That said, I doubt there is one. Commented Nov 25, 2015 at 20:17
  • 1
    @RyanVincent He's asking if there's a built-in function to do exactly what he's doing here I believe. Commented Nov 25, 2015 at 20:19

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree. You could take a "shortcut" by making a function such as 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,
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.