Workaround for Basic Syntax Not Being Parsed
PHP's strict syntax rules can be a hurdle when defining class properties with complex default values. While syntax like (1 << 0) might seem straightforward, PHP considers it an expression with side effects, not a valid default value in class declarations.
Understanding PHP's Class Declaration Limitations
In PHP, default values for class constants or properties must be primitive values, such as:
const ABC = 8; static $GHI = 15;
This restriction stems from the principle that declarative statements should not create side effects.
Creating User-Defined Types and Initializing with Expressions
To overcome this limitation, we can create user-defined types and initialize them with expressions outside the class declaration:
class SDK { // Example of self-created type static private $STRING_NONE = 1 << 0; } $fString = SDK::$STRING_NONE;
Refactoring the Original Class
Applying this workaround to the original class example:
class SDK { static private $_types = null; static public function getType($type_name) { self::_init_types(); return self::$_types[$type_name]; } static private function _init_types() { if (!is_array(self::$_types)) { self::$_types = array( 'STRING_NONE' => 1 << 0, // ... rest of types here ); } } function __construct($fString = null) { if (is_null($fString)) { $fString = self::getType('STRING_NONE') & self::getType('STRING_HOSTS'); } } } $SDK =& new SDK(SDK::getType('STRING_HOSTS'));This approach allows us to define and use types within the class while accommodating default values that are the result of expressions.
The above is the detailed content of How to Define Class Properties with Complex Default Values in PHP. For more information, please follow other related articles on the PHP Chinese website!