0

I'd like to use a string variable to initialize an object. Is something like this possible?

$class = "MyClass";
$x = new $class();
return $x;

Edit: Ha, so when I tried to test this and it didn't work I had a syntax error somewhere else in my script. Apparently this works just fine. Neat.

2
  • 2
    Why don't you try it and see? Commented Apr 11, 2017 at 1:34
  • 1
    Yes it is possible! Commented Apr 11, 2017 at 1:35

1 Answer 1

2

Yes. Its possible in PHP.

$className = 'MyClass';
$object = new $className; 

Attaching PHP documentation snippet on new operator enter image description here

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

2 Comments

Why need to remove bracket ! I want to know !
Actually it works with Brackets as well, updated the answer.

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.