Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one prevent nested function calls?

Tags:

php

nested

First question, please forgive me if I do something wrong or this is a duplicate, I couldn't find another question similar.

I'm writing a very basic translater function i18n($string1) that, when given $string1, queries an index. If the string matches something in the index, it returns the translation $string2. If $string1 doesn't exist in the index, a new entry is created in the index that the user can later write a translated $string2 into.

The issue I want to try and solve is that a sloppy developer (me) might accidentally make a call i18n(i18n($string1)). The way this resolves is that the inner call finds $string1 in the index, returns $string2, then passes that to the function again which tries to find $string2 in the index. This would fail because $string2 is the translation and it would prompt the user to translate the translation... which isn't helpful.

I believe what I want is, in the case that the function is called nested within itself, it returns the string $string1. Thus, it doesn't matter how many times I call i18n within itself, it always translates the string $string1.

What is the best way to do this? I considered using a static or global $isCalled variable, or a singleton, but I've been told in the past that these solutions are almost certainly evil and there's probably something better.

Thanks in advance!

like image 813
Marcus Harrison Avatar asked Jun 10 '26 07:06

Marcus Harrison


1 Answers

You have been told right.

You could go by analyzing the debug_backtrace(), but that is really time and ressources consuming. Also it is an not needed overhead of the translation function.

If a developer calls the translation function with an already translated string it is the developers responsibility to fix that problem not the softwares.

A way to avoid this double calling is to use PHP_CodeSniffer and define coding standars which would forbid such usage. It would be though tough to check for those things if both functions are not in the same line.

like image 115
func0der Avatar answered Jun 11 '26 20:06

func0der



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!