Previous topic

< Configuration File

Next topic

Phpinfo() sections >

This Page

Extension GlobalsΒΆ

PHP extensions provide a way to define globals within an extension. Reading/writing globals should be faster than any other global mechanisms (like static members). You can use extension globals to set up configuration options that change the behavior of your library.

In Zephir, extension globals are restricted to simple scalar types like int/bool/double/char, etc. Complex types such as string/arrays/objects/resources aren’t allowed here.

You can enable extension globals by adding the following structure to your config.json:

{
    //...
    "globals": {
        "allow_some_feature": {
            "type": "bool",
            "default": true
        },
        "number_times": {
            "type": "int",
            "default": 10
        },
        "some_component.my_setting_1": {
            "type": "bool",
            "default": true
        },
        "some_component.my_setting_2": {
            "type": "int",
            "default": 100
        }
    }
}

Each global has the following structure:

"<global-name>": {
    "type": "<some-valid-type>",
    "default": <some-compatible-default-value>
}

Compound globals have the following structure:

"<namespace>.<global-name>": {
    "type": "<some-valid-type>",
    "default": <some-compatible-default-value>
}

Inside any method you can read/write extension globals using the built-in functions globals_get/globals_set:

globals_set("allow_some_feature", true);
let someFeature = globals_get("allow_some_feature");

If you want to change these globals from PHP a good option is enable a method aimed at this:

namespace Test;

class MyOptions
{

    public static function setOptions(array options)
    {
        boolean someOption, anotherOption;

        if fetch someOption, options["some_option"] {
            globals_set("some_option", someOption);
        }

        if fetch anotherOption, options["another_option"] {
            globals_set("another_option", anotherOption);
        }
    }
}

Extension globals cannot be dynamically accessed since the C-code generated by globals_get/globals_set optimizers must be resolved at compilation time:

let myOption = "someOption";

//will throw a compiler exception
let someOption = globals_get(myOption);