PHP - 使代码更高效/更专业


PHP - Making code more efficient/professional

我正在做一个PHP作业,我基本上让一切都工作了。然而,由于我对PHP的了解有限,代码看起来有点太简单了。它的作用是根据输入的工时和工资计算总工资。

你们有什么建议可以让它更好/更短、更高效吗?

<?php
$hours = $_GET ["hours"];
$wages = $_GET ["wages"];
if (empty($hours)) 
{
    echo "Amount of hours worked is required. <br />";
}
if (empty($wages)) 
{
    echo "Employee wage is required. <br />";
}
if (!is_numeric($hours) and ($wages) && !empty ($hours) and ($wages)) 
{
    echo "Please enter numeric numbers only. <br />";
}
if (!empty($hours) and ($wages)) 
{
    if (is_numeric($hours) and ($wages)) 
    {
         if ($hours <= 40) 
         {
        $totalPay = $hours * $wages;
        echo "Your total pay is $ $totalPay";
         }
         if ($hours > 40) 
         {
        $totalPay = ((40 * $wages) + (($hours - 40) * $wages * 1.5));
        echo "Your total pay is $ $totalPay";   
         }
    }
}       
else 
{
    echo "Unable to calculate total pay.";
}

?>

您可以通过实现validate函数使其更简单

function validate($time, $fee)
{
    if(!is_numeric($time) || empty($time)) // ...etc
    {
         return false;
    }
    return true;
} 
if(validate($_GET['hours'], $_GET['wages']))
{
    // do your calculation
}
else
{
    // display error
}