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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?