How to Define Class Properties with Complex Default Values in PHP

Susan Sarandon
Release: 2024-10-20 13:47:02
Original
290 people have browsed it

How to Define Class Properties with Complex Default Values in PHP

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;
Copy after login

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;
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!