0

我有以下代码。最后我把我在服务器上的结果放在评论中。希望有人可以解释为什么结果不同,尽管计算是相同的。

<?php 
date_default_timezone_set('UTC'); 

function formatHourToTime($input){ 
    if (strpos($input, '.') !== false){ 
            $array = explode(".",$input); 
    } 
    elseif (strpos($input, ':') !== false){ 
            $array = explode(":",$input); 
    } 
    elseif (strpos($input, ',') !== false){ 
            $array = explode(",",$input); 
    } 
    elseif ($input >= '0' & $input < '24'){ 
            $array = array($input); 
    } 
    else { 
            $time = false; 
            exit(); 
    } 
    $time = $array[0]*3600+$array[1]*60+$array[2]; 
    return $time; 
} 

$matin_d = 0; //midnight timestamp 0.00 
$matin_f = 10800; //ts de 3h00 
$soir_d = 79200; //ts de 22h00 
$soir_f = 82799; //ts de 23h59:59 

function nightwork($start, $end){ 

    if ($start < $matin_f && $end > $soir_d) $totalheures = ($matin_f - $start)/2 + ($end - $soir_d)/2+100000; 
    elseif ($start < $matin_f && $end < $matin_f) $totalheures = ($end - $start)/2+200000; 
    elseif ($start >= $soir_d && $end > $soir_d) $totalheures = ($end - $start)/2+300000; 
    elseif ($start < $matin_f) $totalheures = ($matin_f-$start)/2+400000; 
    elseif ($end>$soir_d) $totalheures = ($end-$soir_d)/2+500000; 
    else $totalheures = 0+600000;  

    return $totalheures; 
} 

$start = formatHourToTime('07:39:00')*1; 

$end = formatHourToTime('08:00:00')*1; 
$shiftnw = nightwork($start, $end); 
if($start >= $soir_d && $end > $soir_f) $bool = 'true'; 
else $bool = 'false'; 
//même code que la fonction nightwork 
    if ($start < $matin_f && $end > $soir_d) $totalheures = ($matin_f - $start)/2 + ($end - $soir_d)/2+100000; 
    elseif ($start < $matin_f && $end < $matin_f) $totalheures = ($end - $start)/2+200000; 
    elseif ($start >= $soir_d && $end > $soir_d) $totalheures = ($end - $start)/2+300000; 
    elseif ($start < $matin_f) $totalheures = ($matin_f-$start)/2+400000; 
    elseif ($end>$soir_d) $totalheures = ($end-$soir_d)/2+500000; 
    else $totalheures = 0+600000;  

echo $start.' '.$end.'<br>'; 
echo $totalheures. ' ' .$shiftnw;  
//$totalheures is calculated following the script
//while $shiftnw is calculated by calling the function having the same lines 
// prints : 
// 27540 28800 
// 600000 300630 
?>
4

1 回答 1

1

看来问题是在nightwork()函数中您无权访问这些变量:

$matin_d = 0; //midnight timestamp 0.00 
$matin_f = 10800; //ts de 3h00 
$soir_d = 79200; //ts de 22h00 
$soir_f = 82799; //ts de 23h59:59

而您确实可以在脚本末尾计算的全局范围内访问它们。

您还需要将这些值放在函数中,将它们作为参数传递给函数,将它们声明为global函数内部,或者将它们定义为常量,以便它们可用于脚本的所有区域,而不管范围如何。

于 2013-01-09T22:49:12.487 回答