Use constant as class name
Asked Answered
T

3

7

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 ?

Tabulate answered 2/2, 2013 at 13:1 Comment(1)
Perhaps if you state what you actually want to do, there could be some better alternative ways. This may be an XY ProblemMucilaginous
P
5

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...

Paleo answered 2/2, 2013 at 13:14 Comment(1)
An update on this: From PHP 7, you can simply do: echo (CLASSNAME)::$name;Centra
A
0

I was looking into this problem because the class is based on a certain context that has to be given. So I made a function in my class that will return the class you require like so:

/**
 * 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 by using $class = new $this->getClass(static::CLASSNAME); when you defined a constant within the current class that holds the name of the class you want to instantiate. In your case you can use it without the 'static::' or with whatever variable you'd like to use. Do not forget to implement some error handling.

Abercrombie answered 10/7, 2017 at 14:26 Comment(0)
J
-1

Use PHP's absolute mess of dereferencing:

$CLASSNAME = 'a';
$a::$name;
Johny answered 2/2, 2013 at 13:9 Comment(1)
I guess you meant $CLASSNAME::$name, cause this doesn't make sense, but even then, that's not what the OP asked for. You could do $class = CLASSNAME; $class::$name, though.Undertint

© 2022 - 2024 — McMap. All rights reserved.