fixed code when dealing with circular references

Fix for #120 (thanks @davedevelopment). At least, it's behaving "correctly" when there is a circular reference. Not sure if this is worth fixing, but that would make the PHP and C implementations behave in the same way as the C version already segfaults in such a case.