doujiyan0031 2015-06-24 19:23
浏览 29

来自表达式的PHP const

I have a class (MetricUnits) that looks like this:

class MetricUnit {
    const SIZE = [
        "value" => 0,
        "text" => Yii::t("app", "Size")
    ];
}

Yii::t is a i18n function. As you'd be probably thinking by now, this is invalid as PHP doesn't allow expressions in const.

How can I avoid that limitation so I could get the text of that cons?

Btw, Yii::t doesn't take any non-string values, not even const values, so I can't do something like:

class MetricUnit {
    const SIZE = [
        "value" => 0,
        "text" => "Size"
    ];
}

Yii::t("app", MetricUnit::SIZE["text"]);
  • 写回答

1条回答 默认 最新

  • douzhengyi5022 2015-06-24 19:52
    关注

    As it was mentioned, you cannot run calculations like that -

    Furthermore, since you have to do some calculation to get that attribute, then technically, it isn't really a constant value constant -

    So, I would recommend you do this:

    class MetricUnit {
    
         public static $SIZE;
    
         public static getSize(){
              return self::$SIZE ? : self::$SIZE = array(
                 "value" => 0,
                 "text" => Yii::t("app", "Size")
             );
         }
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?