Reputation: 695
I need to access a const like this:
dump (Accomodation::MAX_IMAGES);
but I only have the string class name but not the class itself. For example, I have this string 'AppBundle:Accomodation' but I don't have the class Accomodation
to access its static properties.
Any idea for Symfony?
Upvotes: 0
Views: 4387
Reputation: 39370
You can use the constant function as follow:
$constant = 'MAX_IMAGES';
$className = Accomodation::class; // or AppBundle\Classes\Accomodation
$classWithConstant = sprintf('%s::%s', $className, $constant);
dump(constant($classWithConstant));
Hope this help
Upvotes: 0
Reputation: 21492
If the constant name is static, then access it directly:
echo $class_name::CONSTANT_NAME;
If, however, the constant name is a variable, use Reflection:
$rc = new ReflectionClass($class_name);
echo $rc->getConstant($const_name);
Example
namespace MyNs;
class A {
const C = 1;
}
$class_name = '\MyNs\A';
$c = 'C';
// method #1
echo $class_name::C, PHP_EOL;
// method #2
$rc = new \ReflectionClass($class_name);
echo $rc->getConstant('C'), PHP_EOL;
Upvotes: 1