Sunday, October 14, 2007

Learn PHP In 5 Minutes

Maybe you've noticed a theme in some of my blog posts, the idea of switching back and forth between languages, or quickly transitioning from one language to another.

Recently, I found myself writing some PHP code after a long stretch of doing nothing but Perl, Python, and Javascript. I decided to make it more challenging by writing the syntax from hazy, long-ago memory, and only looking anything up after the fact, to fix the syntax errors. That experience reinforced my feeling ever since Perl came out, that every recent language can be thought of as a series of small deltas to existing languages. (C'mon, don't tell me you didn't look at the little-used report format of Perl, and say to yourself "hey, this is straight out of COBOL!" :-)

So, here's my 5-minute quickstart for PHP. (No APIs, just basic language features.)

Semicolons are mandatory as in Perl, not optional as in Javascript.

Inclusion is via the 'require' keyword, or 'require_once' if everything is requiring everything else. What goes in the included files is flexible as in C and Perl.

Variables are done like Perl, introduced by $. Unlike Perl, arrays and hashes are also notated with $, no @ or % to be found. All subscripts are square brackets.

If, braces, for, while, arithmetic, etc. are like C, C++, Java, and Javascript. No "elsif", it's "else if". Comparison operators are == et. al.

Just to confuse you, HERE documents are introduced by a <<<, 3 instead of 2 like normal. There's a semicolon after the final HERE / EOF / END / etc., but none on the initial line.

Output is largely echo as in shell scripts. Variable interpolation the same as shell scripts and Perl, i.e., the meaning of double quotes and single quotes. String concatenation is . like in Perl, not + like in Javascript. (Use + with strings and you'll get a numeric 0 result.)

Ternary conditions require more quoting than in Javascript, if you're used to stringing together several object-detection tests in a single assignment statement.

Comments are a mishmash of several languages. /* */ like everything except Perl, // like Javascript, # like Perl.

Functions are introduced with the 'function' keyword, and parameters are named (including the $) but not typed. E.g. 'function myfunc($myparm) {...}'.

And that's it. Regular expressions, the other interesting aspect of most language syntax, are done with function-style notation, so on a technicality I don't consider them part of the 5-minute tour.

1 comment:

Noons said...

"every recent language can be thought of as a series of small deltas to existing languages"


interesting thought.

and quite true, IMHE.