What in layman's terms is a Recursive Function using PHP

前端 未结 16 1149
庸人自扰
庸人自扰 2020-11-22 05:50

Can anyone please explain a recursive function to me in PHP (without using Fibonacci) in layman language and using examples? i was looking at an example but the Fibonacci to

16条回答
  •  失恋的感觉
    2020-11-22 06:35

    Recursion is something that repeats itself. Like a function that calls itself from within itself. Let me demonstrate in a somewhat pseudo example:

    Imagine you're out with your buddies drinking beer, but your wife is going to give you hell if you don't come home before midnight. For this purpose, let's create the orderAndDrinkBeer($time) function where $time is midnight minus the time it takes you to finish your current drink and get home.

    So, arriving at the bar, you order your first beer and commence the drinking:

    $timeToGoHome = '23';  // Let's give ourselves an hour for last call and getting home
    
    function orderAndDrinkBeer($timeToGoHome) {  // Let's create the function that's going to call itself.
        $beer = New Beer();  // Let's grab ourselves a new beer
        $currentTime = date('G'); // Current hour in 24-hour format
    
        while ($beer->status != 'empty') {  // Time to commence the drinking loop
            $beer->drink();  // Take a sip or two of the beer(or chug if that's your preference)
        }
    
        // Now we're out of the drinking loop and ready for a new beer
    
        if ($currentTime < $timeToGoHome) { // BUT only if we got the time
            orderAndDrinkBeer($timeToGoHome);  // So we make the function call itself again!
        } else {  // Aw, snap!  It is time :S
            break; // Let's go home :(
        }
    }
    

    Now let's just hope you weren't able to drink enough beer to become so intoxicated that your wife is going to make you sleep on the couch regardless of being home on time -.-

    But yeah, that's pretty much how recursion goes.

提交回复
热议问题