简体   繁体   中英

PHP static function self:: in joomla JFactory class explanation?

Hi I'm looking at the code of Joomla and trying to figure out what exactly happends in this function.

index.php makes a call to function

$app = JFactory::getApplication('site');

jfactory.php code

public static function getApplication($id = null, $config = array(), $prefix='J')
{
    if (!self::$application) {

        jimport('joomla.application.application');

        self::$application = JApplication::getInstance($id, $config, $prefix);
    }

    return self::$application;
}

application.php code..

public static function getInstance($client, $config = array(), $prefix = 'J')
{
    static $instances;

    if (!isset($instances)) {
        $instances = array();
    }

    ....... more code ........

    return $instances[$client];
}

Now I cannot figure out in function getApplication why is self:$application used.

self::$application = JApplication::getInstance($id, $config, $prefix);

$application is always null, what is the purpose of using this approach. I tryied modifying it to

$var = JApplication::getInstance($id, $config, $prefix);

and returnig it but it doesn't work.

I would be very glad if someone with more knowledge could explain what is happening here detailed as possible. Many thanks.

self:: is used to access static members of a class.

So in this case, self::$application is used to cache the application object within JFactory to avoid multiple calls to JApplication::getInstance which is more expensive.

For more info on statics, see Static Keyword .

getApplication() - Returns a reference to the Global JApplication object. Read more

self::$member for static members to be accessed.

Here is an explanation as far I can understand.

if (!self::$application){ //<-check for the $application static variable of the the class

jimport('joomla.application.application');        
self::$application = JApplication::getInstance($id, $config, $prefix);

//if it does not exist get a new instance otherwise nothing happens because there is no else part 
}

return self::$application; //<- return the object(new one or the existing one)

What this does is if $application exist a function call is saved. If not get a new instance. Read more . Hope this helps you out.

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