• Services

Container object

When programming a Includable Module in PHP, there are a bunch of variables that link your module to classes that enable you to get user information, interact with the database and access API’s of the Includable Core.

When running a module, the $this variable refers to the Container object, which is the parent class for all these API’s.

The api controller works a bit differently: the first parameter of the function called contains the Container object.

Globals inside functions inside modules

Yes, we went there: because modules run inside the Container object (referred to as $this), it is not as easy as usual to retrieve global variables in functions, because every variable is defined as a child of a function of the Container class, not as a global variable. You can fix this by defining the variable you want to share with your functions as a global before giving it a value. This approach also applies when working with classes.

<?php

// Explicitly define your variable as a global
global $shared_variable;
$shared_variable = 2048281;

// Doesn't work
function wrong_way_to_get_shared_variable(){
    echo $shared_variable; // Outputs: nothing - might raise an 'undefined' notice though
}

// Works
function right_way_to_get_shared_variable(){
    global $shared_variable;
    echo $shared_variable; // Outputs: 2048281
}

// Sidenote: please never, ever, name your PHP functions like that.

This is the way we designed the modules sandbox, and it may be seen as a flaw, but it also results in more secure module code: non-global variables cannot be accessed by any hook modules or other code outside your module, except for when they are defined as a child of$this (i.e. $this->variable = "value"; – where $this referes to the Container object, which is globally defined).