doutun1362 2015-03-10 19:41
浏览 47
已采纳

PHP关联数组与静态变量键或值ERROR

I have a class that contains some static public variables containing numeric values and an associative static array that matches the numeric values with strings.

However, php doesn't let me do that, it says : Parse error : syntax error, unexpected "$TYPE_DATE" (T_VARIABLE), expecting identifier (T_STRING)

Here is the simplified code:

class myclass
{
    public static $TYPE_DATE = 0b00010010;
    public static $TYPE_INT = 0b01010001;
    private static $types = array( "DATE"=>myclass::$TYPE_DATE, "INTEGER"=>myclass::$TYPE_INT);
}

Thank's in advance

  • 写回答

1条回答 默认 最新

  • doushadu0901 2015-03-10 19:49
    关注

    I think you cannot use static vars to be a reference for other static vars. You can do it with a const.

    class myclass
    {
        const TYPE_DATE = 0b00010010;
        const TYPE_INT = 0b01010001;
        private static $types = array( "DATE"=>self::TYPE_DATE, "INTEGER"=>self::TYPE_INT);
    
        public function __construct() {
    
            print_r(self::$types);
        }
    }
    
    $class= new myclass();
    

    The Output is: Array ( [DATE] => 18 [INTEGER] => 81 )

    Another way is to set $types via a call of an init-function:

    class myclass
    {
        private static $TYPE_DATE = 0b00010010;
        private static $TYPE_INT = 0b01010001;
        public static $types;
    
        public static function init() {
            self::$types = array( "DATE"=>self::$TYPE_DATE, "INTEGER"=>self::$TYPE_INT);
        }
    }
    myclass::init();
    print_r(myclass::$types);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度