Recursion (php3/4/5.0)
Carl on mrt 2nd 2011 07:34 am |
Tags: php, recursion
Recursion should work fine in the latest versions. However, if it doesn’t read on and try another way …
PHP can be a bitch … One problem you will certainly encounter is when you want to call a function recursively. After you have been sweating on your code for half a day, a day, or maybe even longer, you will find that the initial value of your array|hash is no longer the same. It suddenly has diminished to a single value …
However, you can call a method recursively, not a function. Confusing? Yes, quite, as this means that you will only be able to use recursion in a class/object. It may seem you are writing functions in a class – you define them with ‘function’ – but it is a method your creating.
To call a method recursively, you cannot use the default way you would call a class method: ‘$this->methodname ([all your paramaters]);’. Recursion can only be established with: ‘classname::methodname([all your params);’. If you use the first method ‘$this->…’ you will experience the same frustration as with calling a normal function recursively. However, the second way to call your method – ‘class::method ..’ – puts you variable in a new instance, which does not know an previous values, and thus you can iterate recursively over your array|hash.
P.s. Watch out with static methods/functions
Filed in PHP @en