将相应使用的函数名称更改为 IF/ELSE 语句
Change the name of a function used accordingly to a IF/ELSE statement
我不是PHP方面的专家,所以这是困扰我很长时间的事情。我可以接受它,但如果我能找到答案,它可以大大改进我的编码!假设我有一种情况 — IF / ELSE — 必须执行完全相同的 cod,但内部具有不同的功能。示例:
我有什么:
if ($page == 'native') {
// Native page
$title = institutional_settings($id, 'title');
$text = institutional_settings($id, 'text');
$img = institutional_settings($id, 'img');
(... more ... more ... more... )
} else {
// Custom page
$title = personal_settings($id, 'title');
$text = personal_settings($id, 'text');
$img = personal_settings($id, 'img');
(... more ... more ... more... )
}
...你看到了吗?重复代码较多
我想要达到的目标:
if ($page == 'native') {
// Native page
Here I need to instruct my code to use the "institutional_settings()" function
with an alias, like "the_magic()" function
} else {
// Custom page
Here I need to instruct my code to use the "personal_settings()" function
with an alias, like "the_magic()" function
}
// And then, I do not need to repeat the code!
// Here is the magic...
$title = the_magic($id, 'title');
$text = the_magic($id, 'text');
$img = the_magic($id, 'img');
(... more ... more ... more... )
我希望我对这个想法很清楚。
谢谢大家!
G.
您可以轻松地将函数名称存储为变量并使用 call_user_func_array:
调用该函数
$my_func = $page == 'native' ? 'institutional_settings' : 'personal_settings';
$title = call_user_func_array($my_func, [$id, 'text']);
或如评论中所述,Jeto, you could call that function as variable function:
$my_func = $page == 'native' ? 'institutional_settings' : 'personal_settings';
$title = $my_func($id, 'text');
我不是PHP方面的专家,所以这是困扰我很长时间的事情。我可以接受它,但如果我能找到答案,它可以大大改进我的编码!假设我有一种情况 — IF / ELSE — 必须执行完全相同的 cod,但内部具有不同的功能。示例:
我有什么:
if ($page == 'native') {
// Native page
$title = institutional_settings($id, 'title');
$text = institutional_settings($id, 'text');
$img = institutional_settings($id, 'img');
(... more ... more ... more... )
} else {
// Custom page
$title = personal_settings($id, 'title');
$text = personal_settings($id, 'text');
$img = personal_settings($id, 'img');
(... more ... more ... more... )
}
...你看到了吗?重复代码较多
我想要达到的目标:
if ($page == 'native') {
// Native page
Here I need to instruct my code to use the "institutional_settings()" function
with an alias, like "the_magic()" function
} else {
// Custom page
Here I need to instruct my code to use the "personal_settings()" function
with an alias, like "the_magic()" function
}
// And then, I do not need to repeat the code!
// Here is the magic...
$title = the_magic($id, 'title');
$text = the_magic($id, 'text');
$img = the_magic($id, 'img');
(... more ... more ... more... )
我希望我对这个想法很清楚。 谢谢大家!
G.
您可以轻松地将函数名称存储为变量并使用 call_user_func_array:
调用该函数$my_func = $page == 'native' ? 'institutional_settings' : 'personal_settings';
$title = call_user_func_array($my_func, [$id, 'text']);
或如评论中所述,Jeto, you could call that function as variable function:
$my_func = $page == 'native' ? 'institutional_settings' : 'personal_settings';
$title = $my_func($id, 'text');