简体   繁体   中英

Static instance array in instance method

The I18n class in CakePHP provides this method to create instances:

public static function getInstance() {
    static $instance = array();
    if (!$instance) {
        $instance[0] = new I18n();
    }
    return $instance[0];
}

Among other considerations (please correct me if I'm wrong), I understand it helps to use class instances from the convenience functions :

/**
 * Returns a translated string if one is found; Otherwise, the submitted message.
 */
function __($singular, $args = null) {
    // ...
    $translated = I18n::translate($singular);
    // ...
}
echo __('Hello, World!');

This looks cleaner than having to pass the instance around as argument (or, even worse, using a randomly named global variable). But I can't imagine a reason why $instance is an array rather than a plain object.

What can be the purpose of using a one-item array to store class instances?

I would suspect this to be leftovers from older PHP4/CakePHP versions where the instances were assigned by reference.

https://github.com/cakephp/cakephp/blob/1.2.0/cake/libs/i18n.php

function &getInstance() {
    static $instance = array();
    if (!$instance) {
        $instance[0] =& new I18n();
        $instance[0]->l10n =& new L10n();
    }
    return $instance[0];
}
$_this =& I18n::getInstance();

Assigning by reference doesn't work with static , the reference is not being remembered , but it works when assigned to an array entry .

So this was most probably just a workaround for a PHP limitation.

One possible reason for this is to keep all singleton class instances in one global - ( static is a synonym of global in this case ) array variable for monitoring or not messing the global/local namespace with individual variables for each singleton. If each of the static variables were with random names eg $translated it would be more easier to overwrite and mess its value. - bug again for me, this is extremely rear possibility.

For example the I18Nn instance would be with [0] key, other class would have other key. You should check outher singleton classes how manage the static $instance array values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM