使用PHP 5.6,并将在未来12-18个月内针对此特定应用程序迁移到7.0。
所以我们有一个非常大的全局配置文件 - 现在接近100个变量(每次更新都会有更多)。正如您所料,此配置文件由应用程序中的每个脚本页面调用,但并非所有配置值都在所有情况下使用 - 但为了方便起见,我们将它们全部放在同一个文件中。
但我认为将值放入函数可能更有效率,但由于我不是PHP语言(或任何语言)的架构师,我不知道使用函数是否更有效,效率更低,或几乎没有区别。
所以这是一个示例场景。在我们的配置文件中,我们有类似的内容:
$g['user']['enable_username_change'] = true;
$g['user']['enable_image_change'] = true;
$g['user']['display'] = "[LASTNAME], [FIRSTNAME]";
$g['user']['sort_by'] = "[LASTNAME]";
$g['user']['default_locale'] = "english";
$g['user']['profile_page'] = file_get_contents('profile_template.html');
这些值可供所有脚本使用,但只有极少数需要它们。显然我们通过这样做来访问它们:
if ( $g['user']['enable_username_change'] == true ) {
// the code to enable it ...
}
所以我想通过这样的方式改变它的工作方式(如果能提高效率):
function user__getGlobalConfig( $in_param_name ) {
// DEFINE THE VALUES
$g['user']['enable_username_change'] = true;
$g['user']['enable_image_change'] = true;
$g['user']['display'] = "[LASTNAME], [FIRSTNAME]";
$g['user']['sort_by'] = "[LASTNAME]";
$g['user']['default_locale'] = "english";
$g['user']['profile_page'] = file_get_contents('profile_template.html');
if ( isset( $g['user'][$in_param_name] == true ) {
return $g['user'][$in_param_name];
} else {
return false;
}
}
然后我们会像这样访问它:
if ( user__getGlobalConfig('enable_username_change') == true ) {
// the code to enable it ...
}
所以看起来file_get_contents()类型的值只会在调用函数时被读入,我认为这样会更有效,但我可能错了。其他真/假或简单的基于文本的值看起来似乎不是一个很大的效率增益,但我在这里提出 - 任何科学或基于事实的推理,为什么一种方式比另一种更有效?
感谢。
答案 0 :(得分:2)
如果使用函数方法,则应对其进行编码,以便每次都不会通过使用静态变量来缓存设置来重新创建数组。特别是,每次查找设置时,您都不希望它拨打file_get_contents()
。
function user__getGlobalConfig( $in_param_name ) {
static $g;
if (!isset($g)) {
$g = array();
// DEFINE THE VALUES
$g['user']['enable_username_change'] = true;
$g['user']['enable_image_change'] = true;
$g['user']['display'] = "[LASTNAME], [FIRSTNAME]";
$g['user']['sort_by'] = "[LASTNAME]";
$g['user']['default_locale'] = "english";
$g['user']['profile_page'] = file_get_contents('profile_template.html');
}
if ( isset( $g['user'][$in_param_name] ) ){
return $g['user'][$in_param_name];
} else {
return false;
}
}