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;