如何使这成为PHP函数

时间:2011-09-06 20:39:22

标签: php function

如何将其变为功能?我两次做同样的事情......

我尽量使代码尽可能简洁(考虑到我的新手技能)。如果有更好的方法来检查文件是否存在,代码较少,或者使用较少的代码执行任何操作,请提出建议。

如你所见,我需要 1)检查文件是否存在 2)晚上做好,如果是晚上 3)检查是否存在 4)获取密钥 - 由于某种原因,传入的文本将不匹配字符串密钥100%,这就是为什么我使用字符串匹配而不是=

$today_desc_stripped = trim($today_desc);
foreach ( $icon as $k => $v ) {
similar_text($today_desc_stripped, $k, $p);
if ( $p > 90) {
    $today_desc = $k;
    break;
}   
}
$today_icon = $icon[$today_desc];
// if it's past 6 pm, set temp icon to night icon
if ( file_exists("scripts/weather_icons/".$today_icon.".png") ) { // make sure file exists
if ( $time >= 6 ) {
    $temp = $today_icon."_night";
    if ( file_exists($temp) ) {
        $today_icon = $temp;
    }
}
} else {
//if file doesn't exist
$today_icon = "dunno";
mail($to,$subject,$message."195: Icon array on Line 20 is missing assignment for ".$today_desc_stripped);
}

$fourday_desc_stripped = trim($fourday_desc);
foreach ( $icon as $k => $v ) {
similar_text($fourday_desc_stripped, $k, $p);
if ( $p > 90) {
    $fourday_desc = $k;
    break;
}   
}
$fourday_icon = $icon[$fourday_desc];
// if it's past 6 pm, set temp icon to night icon
if ( file_exists("scripts/weather_icons/".$fourday_icon.".png") ) { // make sure file exists
if ( $time >= 6 ) {
    $temp = $fourday_icon."_night";
    if ( file_exists($temp) ) {
        $fourday_icon = $temp;
    }
}
} else {
//if file doesn't exist
$fourday_icon = "dunno";
mail($to,$subject,$message."218: Icon array on Line 20 is missing assignment for ".$fourday_desc_stripped);
}

1 个答案:

答案 0 :(得分:2)

以下是您需要遵循的步骤:

  • 确定目标
  • 识别差异
  • 识别支持数据

您可以将错误检查放在函数内部或外部。由于我们当前范围内仅为您的错误电子邮件设置了几个变量,我将其留在了函数之外:

$today_icon = getIcon($icon, $today_desc);
if (!$today_icon) {
    mail($to,$subject,$message."195: Icon array on Line 20 is missing assignment for ".$today_desc);
}

$fourday_icon = getIcon($icon, $fourday_desc);
if (!$fourday_icon) {
    mail($to,$subject,$message."195: Icon array on Line 20 is missing assignment for ".$fourday_desc);
}

对于函数本身:

function getIcon($icons, $icon_name_request) {
    $icon_name = trim($icon_name_request);

    foreach ( $icons as $k => $v ) {
        similar_text($icon_name, $k, $p);
        if ( $p > 90) {
            $icon_name = $k;
            break;
        }   
    }

    $icon_filebase = null;

    // if it's past 6 pm, set temp icon to night icon
    if ( !empty($icons[$icon_name]) && 
        file_exists("scripts/weather_icons/". $icons[$icon_name] .".png") ) {
                 // make sure file exists

        $icon_filebase = $icons[$icon_name];

        if ( $time >= 6 ) {
            $temp = $icon_filebase."_night";
            if ( file_exists($temp) ) {
                $icon_filebase = $temp;
            }
        }
    }
    return $icon_filebase;
}