Use constant as a class name

I need to use a constant as the class name to access this static property of the class, i.e.

class a {

    public static $name = "Jon";

}

define("CLASSNAME", "a");

echo CLASSNAME::$name;

this returns an error, this class CLASSNAMEdoes not exist. Is there any solution?

+5
source share
3 answers

This is possible with a reflection:

class a {

    public static $name = "Jon";

}

define("CLASSNAME", "a");

$obj = new ReflectionClass(CLASSNAME);
echo $obj->getStaticPropertyValue("name");

If this is a good design choice, this is another question ...

+4
source

Use the complete PHP disorder mess:

$CLASSNAME = 'a';
$a::$name;
0
source

, , . , , , :

/**
 * Instantiate a class by class name in variable
 *
 * @param string $className The name of the class
 * @return mixed The instantiated class
 */
protected function getClass($className)
{
    return new $className;
}

Therefore, you can call it using $class = new $this->getClass(static::CLASSNAME);when you defined a constant in the current class that contains the name of the class you want to create. In your case, you can use it without " static::" or with any variable that you would like to use. Remember to do some error handling.

0
source

All Articles