在我的函数中,我有更多变量:
$disallowGallery = 1;
$disallowFriend = 1;
$disallowWall = 1;
$disallowPM = 1;
$disallowStatusComment = 1;
现在,我有一个$ check参数。如果它包含“图库”,则该函数应返回$ disallowGallery变量。如果它包含'Friend',它应该返回$ disallowFriend变量。
我可以用很多if else语句/或开关自己做。但是,是否存在更有效/更简单的方式?
答案 0 :(得分:4)
将这个存放在我眼中的最简洁方法是阵列:
$disallow = array(
"Gallery" => 1,
"Friend" => 1,
"Wall" => 1,
"PM" => 1,
"Comment" => 1
);
在检查功能中,您可以像这样进行检查:
function check("Comment")
....
if (array_key_exists($area, $disallow))
return $disallow[$area];
else
return 0;
答案 1 :(得分:3)
您可以使用variable variables:
function isDisallowed($type) {
$disallowGallery = 1;
$disallowFriend = 1;
$disallowWall = 1;
$disallowPM = 1;
$disallowStatusComment = 1;
$type = "disallowed$type";
return isset($$type) ? $$type : 1;
}
但我更倾向于将配置存储在关联数组中:
function isDisallowed($type) {
$disallowed = array (
'Gallery' => 1,
'Friend' => 1,
// ...
'StatusComment' => 1,
);
return array_key_exists($type, $disallowed) ? $disallowed[$type] : 1;
}
答案 2 :(得分:2)
return ${'disallow' . $check};