duanpiao6679 2011-09-21 20:57
浏览 34
已采纳

使用包含常量名称的简单变量访问类常量

I'm trying to access a class constant in one of my classes:

const MY_CONST = "value";

If I have a variable which holds the name of this constant like this:

$myVar = "MY_CONST";

Can I access the value of MY_CONST somehow?

self::$myVar

does not work obviously because it is for static properties. Variable variables does not work either.

  • 写回答

5条回答 默认 最新

  • dongya4089 2011-09-21 21:03
    关注

    There are two ways to do this: using the constant function or using reflection.

    Constant Function

    The constant function works with constants declared through define as well as class constants:

    class A
    {
        const MY_CONST = 'myval';
    
        static function test()
        {
            $c = 'MY_CONST';
            return constant('self::'. $c);
        }
    }
    
    echo A::test(); // output: myval
    

    Reflection Class

    A second, more laborious way, would be through reflection:

    $ref = new ReflectionClass('A');
    $constName = 'MY_CONST';
    echo $ref->getConstant($constName); // output: myval
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输