Why does PHP have a $ sign in front of variables? [closed]
In PHP and some other scripting languages have the $var
syntax while Java and other languages we can do just var
.
Is there any theory behind it? Does it help them to parse. If not why would they choose to tack on an extra character in front?
It prevents variable names conflicting with language keywords, and allows them to be interpolated in strings.
My theory is that scripting languages such as php would need some way to continue to run even if a new reserved word is introduced, such as php4 -> php5 got catch added. Since its a scripting language any webpages that had catch as a variable name would not die, due to the change in the language.
This is not an issue with compiled languages since everything is converted to a binary and any changes in the language would not affect already compiled programs
Because constants and reserved words come without the $ thing
Don't try to compare programming languages syntaxes... They're right in being so different. :)
Because its roots lay in Perl: PHP History
Because some languages are ugly ad hoc scripting kludges and used goofy tricks to alert the "parser" to the fact that it has work to do.
And other languages were real language design efforts that used real variable names and not ugly macro syntax...
The one rather decent language that uses $
is Perl, but I might point out that Perl6 dropped it.
Here is an proposed explanation as to why PHP uses $. It shows the sequence of original scripts such as awk which used the $ through Perl to PHP.
Probably originally used to make parsing of the language a lot easier.
精彩评论