PHP:如何返回正确的东西
在我的功能我有更多的变量:PHP:如何返回正确的东西
$disallowGallery = 1;
$disallowFriend = 1;
$disallowWall = 1;
$disallowPM = 1;
$disallowStatusComment = 1;
现在,我有一个$检查参数。如果它包含'Gallery',则该函数应该返回$ disallowGallery变量。如果它包含“朋友”,它应该返回$ disallowFriend变量。
我可以自己做很多if else语句/或开关。但是否存在更有效/更简单的方法?
return ${'disallow' . $check};
isset()可能是可取的吗? – 2010-11-12 20:50:46
@jon_darkstar:错误处理留给提问者。 – 2010-11-12 20:52:43
这工作很好。如果它没有用$ check查找任何变量,它不会返回任何内容。 – Johnson 2010-11-12 20:56:23
您可以使用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;
}
存储在这个最干净的方式我眼睛会是阵列:
$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;
只需使用if/else开关concstruct即可。简单易用(也可以阅读)。 – BlueDog 2010-11-12 20:50:52