'Dynamic function call from child namespace

I have several dictionaries in my application for internationalization. Depending on the version of the app, different languages should be included, so it is not necessary to deliver all available languages.

The setting which languages can be used, I want to set in constants for simplicity.

My dictionaries themselves are simple 'getDictionary()' functions that return an array of translations. To distinguish the different languages, the respective functions are in namespaces, e.g. Language\enGB and Language\esMX.

Dictionary for English (Great Britain).

namespace Language\enGB;

function getDictionary(): array
{
    // ...
}

Dictionary for Spanish (Mexico).

namespace Language\enGB;

function getDictionary(): array
{
    // ...
}

The parent class that uses these dictionaries is I18n. This class should dynamically include the dictionaries.

namespace Language;

// Include all available languages.
include_once __DIR__ . '/Dictionary/enGB.php';
include_once __DIR__ . '/Dictionary/enUS.php';
include_once __DIR__ . '/Dictionary/esMX.php';

// Supported languages that can be used by the client.
const SUPPORTED_LANGUAGES = ['en-GB', 'en-US'];

// Function definitions for all
const LANGUAGE_IMPORTS = [
    'en-GB' => 'enGB\getDictionary',
    'en-US' => 'enUS\getDictionary',
    'es-MX' => 'esMX\getDictionary'
];

class I18n
{

    private array $dictionary = [];

    public function __construct(string $isoCode)
    {
        // Call all dictionary functions from all supported languages.
        // Unsupported languages are not included.
        foreach (SUPPORTED_LANGUAGES as $supportedLanguage) {
            $functionName = LANGUAGE_IMPORTS[$supportedLanguage];
            if (!function_exists($functionName)) continue;
            $functionName();
        }
    }
}

Now I have the following problem: I cannot call the functions because they do not exist. The line if (!function_exists($functionName)) continue; always goes to the true case (continue).

I can't quite figure it out since 1) the functions have been included via include_once and 2) the namespace is specified with in the function name. Where is the problem here ?

php


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source