douyi1197 2014-05-25 19:52
浏览 146
已采纳

调用自身的PHP函数始终返回null

I have searched, researched, cursed a lot and shouted at my computer screen repeatedly but nothing seems to work…

I have created the below function to query a mysql database against the current date. If the current date does not exist in the database, the previous days date is generated and the function calls itself again with the new date. This continues until a match is found at which point the function returns an array with the required data.

function getWeekNumber($dateToQuery) {
    $oneDay = 86400;
    $timestamp = $dateToQuery;
    $stringDate = date("d/m/y", $dateToQuery);

    include("inc/dbconx.php");
    try {
        $STH = $DBH->prepare("SELECT `Week_Commencing`,`Week_Number` FROM weeks WHERE `Week_Commencing` = ?");
        $STH->bindParam(1,$stringDate);
        $STH->execute();
    } catch (Exception $e) {
        echo "There was a problem retrieving data from the database";
        exit;
    }

    $result = $STH->fetch(PDO::FETCH_ASSOC);

    if ($result == FALSE) {
        $prevDay = $timestamp - $oneDay;
        getWeekNumber($prevDay);
    } else {
        $output = array("Week_Commencing" => $result['Week_Commencing'], "Week_Number" => $result['Week_Number']);
        var_dump($output);
        return $output;
    }
}

$weekNumber = getWeekNumber($serverTime);
var_dump($weekNumber);

Everything works and you will see where I have included var_dumps to check the results…

The var_dump within the else clause of the function outputs as expected:

array(2) {
    ["Week_Commencing"]=> string(8) "19/05/14"
    ["Week_Number"]=> string(1) "4"
}

However, when I call the function it always returns NULL.

Does anyone know why this is happening?

Thanks in advance

  • 写回答

2条回答 默认 最新

  • duandeng1824 2014-05-25 20:00
    关注
    return getWeekNumber($prevDay);
    ^^^^^^
    

    The function is not magically going to return a value, even from a recursive call, without the return statement.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀