Search code examples
phplanguage-construct

Use constant as class name


I need to use constant as class name for acces to this class static property, that is

class a {

    public static $name = "Jon";

}

define("CLASSNAME", "a");

echo CLASSNAME::$name;

this returns error, that class CLASSNAME not exists. There is some solution ?


Solution

  • It's possible with reflection:

    class a {
    
        public static $name = "Jon";
    
    }
    
    define("CLASSNAME", "a");
    
    $obj = new ReflectionClass(CLASSNAME);
    echo $obj->getStaticPropertyValue("name");
    

    If it is a good design choice is another question...