如何动态访问另一个类的静态属性和静态常量

时间:2015-11-23 05:59:42

标签: php class variables static constants

这是我的PHP示例代码,我想动态访问另一个类的静态属性,基本上我有一个存储在变量中的类名。

# Main Class
class HelloAction
{
    const FIRST = "DEMO";
    public static $first = "WORLD";
    function __construct($confclassname)
    {
        $this->config = $confclassname;
        # PHP Interpreter throws an Error for These Two Lines
        $this->first1 = $this->config::$a;
        $this->first2 = $this->config::$b;
    }

    function setFirst($s)
    {
        self::$first = $s;
    }
}

# Configuration Class
# Can hold only static or constants values
class action1
{
    const AAAA = "____Hello World____";
    public static $a = "this is an apple";
    public static $b = "That is an Dog";
    function __construct()
    {
        $this->second = "hi, there.";
    }
}

# Configuration Class
# Can hold only static or constants values
class action2
{
    const AAAA = "___Yeah, Hello World____";
    public static $a = "Whare You were...";
    public static $b = "Awesome work";
    function __construct()
    {

    }
    public static function action21($s)
    {
        self::$a = $s;
    }
    public function action22()
    {
        return self::$a;
    }
}

# We want to inject configuration Object into Main Class Object
$b1 = new HelloAction('action1');
$b2 = new HelloAction('action2');

echo $b1->first1 . "\n";
echo $b1->first2 . "\n";
  

错误:   解析错误:语法错误,第11行的F:\ xampp \ htdocs \ 6-project-n_demos \ 011.php中的意外“::”(T_PAAMAYIM_NEKUDOTAYIM)

3 个答案:

答案 0 :(得分:0)

出错的行应为

$this->first1 = $confclassname::$a;
$this->first2 = $confclassname::$b;

不允许将$this->config写为类名。它需要一个变量。

如果您写$this->config::$a;,那么口译员可能会将其视为$this->config::$a;。它将config视为属性,并在发现属性旁边有范围解析运算符时给出错误。

我尝试将它封装在像{$this->config}::$a这样的花括号中。它仍然无效。所以我建议只使用变量来定义类名。

答案 1 :(得分:0)

评论专栏byte[]11并尝试12 var_dump,你会发现它并没有选择整个对象而只是this->config因为您在对象上调用静态方法,所以请尝试以下代码             

__construct

答案 2 :(得分:0)

我稍微更改了我的HelloAction类代码,这是我想要的方式工作的解决方案,现在我可以访问Class和Class Methods中的每一个静态属性,常量。

class HelloAction
{
    const FIRST = "DEMO";
    public static $first = "WORLD";
    function __construct($confclassname)
    {
        $this->config = new $confclassname();
        $this->configRefObj = new ReflectionClass($this->config);
        $this->first1 = $this->configRefObj->getStaticPropertyValue("a");
        $this->first2 = $this->configRefObj->getStaticPropertyValue("b");
    }

    function setFirst($s)
    {
        self::$first = $s;
    }
}