Recursion (php3/4/5.0)

Carl on mrt 2nd 2011

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 | Reacties uitgeschakeld

Recursie (php3/4/5.0)

Carl on mrt 2nd 2011

Recursie zou in de huidge versies van php goed moeten werken. Echter, als dat niet het geval is, lees het onderstaande en probeer het alternatief.

PHP is soms niet gemakkelijk te doorgronden. Een van de problemen die je als programmeur geheid tegen zal komen is dat je een functie recursief wilt aanroepen. Als je dan je code zover hebt om te testen, kom je er achter dat de waarde van je initïele variabele ineens niet meer hetzelfde is. Je array of hash bevat niet meer dezelfde waarde(n) maar alleen de eerste …

In PHP kan je een methode recursief aanroepen, niet een functie. Verwarrend? Ja, nogal, want dit wil zeggen dat je alleen in een class/object recursief kan werken. Ondanks dat het lijkt dat je functies schrijft in een class – doordat je ‘function’ gebruikt – zijn het methoden.

Het recursief aanroepen van de methode kan je niet op de gebruikelijke manier: ‘$this->methodname ([all your paramaters]);’. Recursie krijg je alleen voorelkaar met ‘classname::methodname([all your params);’. Indien je het met ‘$this->..’ probeert, zal je merken dat je array|hash wederom is teruggebracht naar één waarde. Dat komt omdat je data zich nog in dezelfde instantie/namespace (of hoe je het ook noemen wilt) bevindt. Daardoor wordt je variabele overschreven. Indien je gebruik maakt van ‘class::method ..’, maak je gebruik van een nieuwe instantie van je class, waar die variabele nog niet in voorkomt.

P.s. Let op met static methods.

Filed in PHP | Reacties uitgeschakeld