views:

595

answers:

4

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?

+34  A: 

It prevents variable names conflicting with language keywords, and allows them to be interpolated in strings.

David Dorward
this is a nice concise answer which really doesn't help much... some examples or details would help
HorusKol
and yet... it matches flawlessly with the question
Jacco
+it's much easier to spot and work with a variable this way.
dusoft
1) In a PHP, a language with about 5700 keywords, namespace conflicts are much more common than in, say, C with about 30 keywords. 2) echo `"Hi, $first '$nick' $last, this is your $num$numext visit."` vs `"Hi, ".$first". '".$nick."' ".$last.", this is your ".$num.$numext." visit.";` - which do you prefer?
SF.
+1  A: 

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

sinrtb
Interpreted languages like Python make do without any variable prefix. Backwards-compatibility breaking changes are held until the next major version of the language.
badp
Perl has sigils **and** is compiled. Sure it's to byte-code, but then again so is `C#` . You should really change *compiled* to *static*, since it is more accurate.
Brad Gilbert
+4  A: 

Because constants and reserved words come without the $ thing

Don't try to compare programming languages syntaxes... They're right in being so different. :)

TiuTalk
+2  A: 

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.

DigitalRoss
The goofy tricks were probably justifiable in the 1970s when it was more important to make code easy on the compiler than easy for a human to read.
Dan
Unfortunately Perl6 did not drop sigils [1] ($, @, %).[1] http://en.wikipedia.org/wiki/Perl_6#Sigil_invariance
nimrodm
**Fortunately** Perl 6 did not drop sigils, otherwise it would no longer be Perl.
Brad Gilbert
`$array[0]` used to _get me a scalar_ from an array (`$`), but now `@array[0]` gets me a scalar _from an array_ (`@`). Why did they have to change one of the few things about good ol' Perl that made sense?
Jon Purdy