Declare an object in PHP using constant to hold class name (like you can do with variables)?



This question about syntax/syntax capabilities in PHP. Take for example, using variables to store class names when declaring objects:

$className= 'myClass';
$obj = new $className;

I was wondering if there were some way to do the same with constants. Something along the lines of:

$obj = new {CLASS_NAME};

This doesn’t work. Obviously I could just use a variable as an intermediary step, but I was mostly just wondering for edification purposes whether this was a formatting issue or if this is just not possible to do directly in this way.


You can’t do this with a sensible expression in PHP, as u_mulder says.

You can do it in one line with reflection.

$obj = (new ReflectionClass(CLASS_NAME))->newInstance();

Any parameters need to go into the newInstance call.

This is a silly idea, not least because having variable behaviour depending on class names in strings probably means bad architecture. Don’t do it. But you asked if it is possible, and yes, it is.

Answered By – lonesomeday

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More