I found an elaborate reference in this SO Q&A on how to check whether variables exist.
It is mentioned that to check whether a class has a certain property, one uses (as documented at php.net):
$check = property_exists('MyClass', 'property_name');
Also, for 'constants' that are 'defined', one could use:
$check = defined('MY_CONSTANT');
Question: how about a const
in a class?
To elaborate... I have a class which I use in several projects, (minimal example):
class ProjectSettings {
const MY_CONSTANT = 'my constant';
}
I'm writing a new feature which requires a 'project setting' but should apply a default value if the setting does not exist in the class.
Note that the same class is used in several projects (with different values). It would be cumbersome to implement this new const in all existing projects. However, the new feature is in an existing script and I may update older projects with this new version, without also updating the ProjectSettings class (for eaxample if this new feature is not even used). That's why I would like to use feature detection.
I'm thinking in the line of:
if (defined(ProjectSettings::MY_CONSTANT)) {
$setting = ProjectSettings::MY_CONSTANT;
} else {
$setting = 'some default value';
}
However, my futile attempts result in:
var_dump(ProjectSettings::MY_CONSTANT);
// string(11) "my constant"
// (as expected)
var_dump(ProjectSettings::MY_OTHER);
// generates a PHP Fatal error
var_dump(defined(ProjectSettings::MY_CONSTANT));
// bool(false)
// (it exists, but is not 'defined', oh well...)
var_dump(defined(ProjectSettings::MY_OTHER));
// generates PHP Fatal error
var_dump(get_class_vars('ProjectSettings'));
// array(0) {
// }
// (MY_OTHER is not there, but neither is MY_CONSTANT...)
var_dump(isset(ProjectSettings::MY_CONSTANT));
// generates a PHP Fatal error
var_dump(null !== ProjectSettings::MY_CONSTANT);
// bool(true)
var_dump(null !== ProjectSettings::MY_OTHER);
// generates a PHP Fatal error
var_dump(constant('ProjectSettings::MY_CONSTANT'));
// string(11) "my constant"
// (as expected)
var_dump(constant('ProjectSettings::MY_OTHER'));
// NULL
// BUT: this generates a PHP Warning
var_dump(property_exists('ProjectSettings', 'MY_CONSTANT'));
// bool(false)
var_dump(property_exists('ProjectSettings', 'MY_OTHER'));
// bool(false)
var_dump(get_defined_constants());
// produces a whole bunch of constants, but not the ones in the class...
The route via constant('ProjectSettings::MY_OTHER')
seems promising, but it generates a PHP Warning. I do not want to get warnings and I do not want to suppress them either...
What method did I miss?