I am using Reflection against the following class:
class Constant {
const CONSTANT = 3;
public $test1 = 'CONSTANT';
public $test2 = CONSTANT;
}
When using ReflectionClass::getDefaultProperties(); I get the following notice:
PHP Notice: Use of undefined constant CONSTANT - assumed 'CONSTANT'
on this line of code:
$defaultValues = $reflectionClass->getDefaultProperties();
First, I wonder why I get the notice here (I mean, I can’t anticipate/avoid the notice even though the code is 100% correct)?
And second, when using var_export($defaultValues[3]), it outputs 'CONSTANT' which is normal because it has been casted to string.
So, how can I output CONSTANT instead of 'CONSTANT' for $test2 and still output a quote-delimited string for $test1?
Edit: I get CONSTANT for both cases ($test1 and $test2) but because of that I can’t differentiate between them. I want to be able to know: that is a string, or that is the name of a constant.
because you mean
self::CONSTANTbut tried to use globalCONSTANT, e.g. your code assumesbut you wanted to do this:
With the latter, this
will give
Is there a way to get
["test2"] => self::CONSTANTvia Reflection? No. The Reflection API will evaluate the constant. If you wantself::CONSTANTyou’d have to try some of the 3rd party static reflection APIs.And obviously, if you want
'CONSTANT', write"'CONSTANT'".Regarding EDIT:
$foo = CONSTANTmeans assign the constant value to the foo property. It does not mean assign the constant itself. By assigning the value to a property, it no longer is a constant value. It’s mutable. The “name of a constant” is represented as a string. You can useReflectionClass::hasConstantto check whether that string happens to also be the name of a defined constant in the class or usedefinedfor global constants.