Unescaped dollar sign doesn't throw error; PHP processing edge case?

410 views Asked by At

I've run into what seems like a strange edge case with the PHP processor. According to the PHP manual:

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

The edge case I've seen is the case where the character immediately after the dollar sign is not a letter or underscore (or some other meta-character combination that would invoke a special meaning, such as a second dollar sign). Here's an example:

$someVariable = "This is a $(test of our edge case).";

I can output this variable with an echo statement, and the dollar sign before the word test shows up with no problem (no escape was necessary). PHP throws no error or warning, as far as I can tell. So now to my question: is this an edge-case in the processor grammar? Is it a bug? Or does this have some other interpretation that I'm overlooking?

I'm well aware that, as a good programming practice, one should always escape the dollar sign in a double-quoted string when one wants to print said character (or one could simply use a single-quoted string). I was just curious as to why this case didn't necessarily require an escape before the dollar sign.

1

There are 1 answers

2
AudioBubble On BEST ANSWER

No, there is no error with the lack of the error message. PHP will only expand valid variables inside of double quoted enclosed strings.

If you are familiar with regular expressions, you can think of it as PHP is matching the contents of double quoted strings with the following expression:

\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*