Not sure how to ask this without rambling about preprocessors in C, but I will try:
Is there a way in PHP, to use the name of a variable as a string or value.
Such that instead of calling function like this,
$somevar = 'whatever';
fun('somevar', $somevar);
you can call it like this:
fun(<magic:$somevar>, $somevar);
or even, dare I say it, like this:
fun($somevar);
and the fun() would itself deduce both the value ('whatever'), and the name ('somevar') of the variable. (In C, it could be done with a preprocessor #define.)
"magic" above is of course a place holder for the magic syntax in PHP I am looking for which will help me do this. I guess it could be made somehow with eval()? But people keep telling me not to use eval.
Someone hinted that introspection might somehow do the trick. Any leads there would be welcome.
No. PHP's scoping rules prevent you from doing that. The only way would be through a pre processor (as you are aware) or by introspecting the code, which would be kind of the same thing. PHP has a built-in tokenizer, that you can use to parse a file with. You can use debug_backtrace
to find out which files to parse through. It's going to be a really messy and inefficient thing to do though, so you would probably be better off rethinking what you're doing.