简体   繁体   中英

How to get class from string class name in Symfony

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?

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM