A recursive function is a function that calls itself. Care must be taken in PHP, however, as your code must not carry out a certain number of recursive function calls. i.e. There must be a mechanism (IF statement, etc) that stops the recursion after the desired result has been found. If you allow your function to carry out an unlimited amount of calls (and you have XDebug installed), you will receive the error: “Fatal error: Maximum function nesting level of ‘100’ reached, aborting!”
Lets take a look at a simple example of a recursive function in PHP:
The code above is pretty simple. Basically, the function checks to see if the number is less than 50. If the number is less than 50, then we increment the number and call the function again. This process is repeated until the number has reached 50.
Note that if you need to go deeper than 100 levels, then you will need to increase the xdebug.max_nesting_level setting. You can do this via the ini_set function if you’re on a hosted platform that allows you to modify PHP ini settings on the fly:
It is worth noting that going over 100 levels of recursion is probably a pretty bad idea! If you are reaching this level, then recursion is probably not the solution that you need!
0 comments:
Post a Comment