Arbitrary PHP question, more/less out of curiosity. I apologize if this is a silly question.
$class = 'ClassName';
$object = new $class();
or
$object = $class::functionName();
This obviously works.
define(CLASS, 'ClassName');
$object = new CLASS();
or
$object = CLASS::functionName();
This does not work.
Just wondering if it is at all possible to use defined constants to create new objects. If not, I definitely understand why.
Well, you can do this:
…but as far as I know, you can’t use the constant directly as in
new MYCLASS(), because it will of course look for the class namedMYCLASS.Side note: You can’t have constants with names that conflict with reserved words, like
classorfunction, even if they are uppercased.You could do something silly like this if for some reason you’re doing this a lot:
…but I don’t really recommend it. I’d also guess that you probably don’t need so many constants, or there’s a more elegant way to do what you’re doing that doesn’t involve constants at all.