【发布时间】:2015-06-09 13:07:06
【问题描述】:
在不使用 Switch 或 If 的情况下如何执行逻辑?
例如 check_id_switch($id)
function check_id_switch($id){
switch($id){
case '1':
$HW = 'Hello, World!';
break;
default:
$HW = 'Goodbye, World!';
break;
}
return $HW;
}
或实例 check_id_if($id)
function check_id_if($id){
if($id == 1){
$HW = 'Hello, World!';
}
else{
$HW = 'Goodbye, World!';
}
return $HW;
}
这两个函数 check_id_switch($id) 和 check_id_if($id) 都会检查 ID 到它的引用。
如何在不使用 php 中的 if/switch 语句的情况下创建与上述相同的逻辑?我也想避免forloops。
关于开关的性能存在多种争论/如果但如果有另一个控制结构,它是否低于或超过上述控制结构?
添加登录脚本作为 if 语句的示例。我已经删除了登录脚本的主干。如果为 true:false,则不需要查看已完成的操作。我只是觉得下面是笨重和不干净的。
if(!empty($_POST))
{
$errors = array();
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$remember_choice = trim($_POST["remember_me"]);
if($username == "")
{
$errors[] = "";
}
if($password == "")
{
$errors[] = "";
}
if(count($errors) == 0)
{
if(!usernameExists($username))
{
$errors[] = "";
}
else
{
$userdetails = fetchUserDetails($username);
if($userdetails["active"]==0)
{
$errors[] = "";
}
else
{
$entered_pass = generateHash($password,$userdetails["password"]);
if($entered_pass != $userdetails["password"])
{
$errors[] = "";
}
else
{
// LOG USER IN
}
}
}
}
}
【问题讨论】:
-
if或多或少是您在编程中可以做的最简单的事情。我敢说它是编程的基础。使用if时几乎没有开销,即使是很多ifs。 -
创建一个简单的数组:
$arr = [1 => "Hello, World!", 2 => "Goodby, World!"];,然后:echo $arr[$id];完成.. -
@Rizier123 我喜欢这种思路,你的回答很有想象力(这是我要求的),但我不认为访问数组是一个很好的替代品。因为您将无法逐步完成诸如注册用户或检查数据表以获取真/假返回的过程。除非你能举出具体的例子吗?
-
如果您想将数组解决方案与回显/返回一个值的更多操作相结合,您可以将函数的名称放入数组中并调用它,而不是回显该值。
-
@Chris 我真的没有得到你最后的评论 ^。但是,如果您询问如何检查 id 是否存在于数组中,只需执行以下操作:
if(isset($arr[$id])),如果您有一个以$id为键的数组元素,这将返回 true,否则返回 false
标签: php if-statement switch-statement logic