Use constant as class name

前端 未结 3 1673
一向
一向 2020-12-20 19:15

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\",         


        
相关标签:
3条回答
  • 2020-12-20 19:44

    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.

    0 讨论(0)
  • 2020-12-20 19:48

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

    0 讨论(0)
  • 2020-12-20 19:55

    Use PHP's absolute mess of dereferencing:

    $CLASSNAME = 'a';
    $a::$name;
    
    0 讨论(0)
提交回复
热议问题