繁体   English   中英

PHP:从字符串中获取类常量的值

[英]PHP: Getting value of constant of class from string

例子如下:

<?php

class test{
    const A = "1";
    const B = "2";

    public function getStr($a){
        echo self::$a;
    }

}

$c = new test();
$c->getStr("A");


 ?>

当我使用 getStr("A") 时,如何在窗口中回显变量“A”

它可以通过ReflectionClass::getConstants来完成。

在此处尝试此代码片段

<?php

ini_set('display_errors', 1);

class test{
    const A = "1";
    const B = "2";

    public function getStr($a){

        $class= new ReflectionClass(self::class);//passing class name to ReflectionClass
        echo $class->getConstant($a);//getting required constant.
    }

}

$c = new test();
$c->getStr("A");

如果您需要检索常量的值,但不知道其名称,则 constant() 很有用。 即它存储在变量中或由函数返回。

常量文档

echo constant("self::".$a);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM