yii2-php where do I use static variables for a function?

Source: Internet
Author: User
Tags yii
Suppose you get the configuration of a Web site

private function _getSettings(){    //static $_settings;    $cache=Yii::$app->cache;    $settings=$cache->get('settings');    if(!$settings){        //获取并设置setting    }    return $settings;}

In this case, should a static variable be set? What are the best conditions for using static variables?

Reply content:

Suppose you get the configuration of a Web site

private function _getSettings(){    //static $_settings;    $cache=Yii::$app->cache;    $settings=$cache->get('settings');    if(!$settings){        //获取并设置setting    }    return $settings;}

In this case, should a static variable be set? What are the best conditions for using static variables?

class .... {    // 如果参数不多    // 或者写到别的文件里    // 其他地方共用也好用,不容易打错    const SETTING_SOME = 'somePerporty';    // 参数多其实应该用数据库了    private function _getSettings()    {        //static $_settings;        $cache=Yii::$app->cache;        $settings=$cache->get({CLASSNAME}::SETTING_SOME);        if(!$settings){            //获取并设置setting        }        return $settings;    }}

Personally think you don't need to use static variables here,
If static local variables are used in a function, he means that the value is still there and cannot be used outside the function each time the function is executed.
You need to update the cache every time you perform this, so there's no need to keep this value.

Note that static variables are distinguished from global variables.

static $s_var;global $g_var;
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.