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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了