Workaround for basic syntax not being parsed

When declaring a class constant or property in PHP you can only specify a primitive values for default values. So for instance, this class declaration won’t work:

class TEST {
 const ABC = 2 * 4;
 const DEF = some_function();
 static $GHI = array(
   'key'=> 5 * 3,
 );
}

But this class declaration will:

class TEST {
 const ABC = 8;
 static $GHI = 15;
}

These rules apply to default values for class constants/properties – you can always initialize other variables with the results of an expression:

$a= array(
 'a'=> 1 * 2,
 'b'=> 2 * 2,
 'c'=> 3 * 2,
);

The reason for this class declaration behavior is as follows: expressions are like verbs. They do something. Classes are like nouns: they declare something. A declarative statement should never produce the side-effects of an action statement. Requiring primitive default values enforces this rule.

With this in mind we can refactor the original class as follows:

class SDK
{

    static protected $_types= null;

    static public function getType($type_name) {
        self::_init_types();
        if (array_key_exists($type_name, self::$_types)) {
            return self::$_types[$type_name];
        } else {
            throw new Exception("unknown type $type_name");
        }
    }

    static protected function _init_types() {
        if (!is_array(self::$_types)) {
            self::$_types= array(
                'STRING_NONE'=> 1 << 0,
                // ... rest of the "constants" here
                'STRING_HOSTS'=> 1 << 6
            );
        }
    }

    function __construct($fString = null) {
        if (is_null($fString)) {
            $fString= self::getType('STRING_NONE') & self::getType('STRING_HOSTS');
        }
        var_dump($fString);
    }

}

$SDK &= new SDK(SDK::getType('STRING_HOSTS')); 

Leave a Comment