Notes on PHP

22/10/09

PHP Tags
tags enclose PHP code when mixed with HTML. Abbreviated tag not good. Don't use ?> in PHP only file - not required and can cause problems with trailing whitespace.

Comments
As for C++.
Comment conventions for Drupal:
/**
* Open comment as above.
* Succeeding lines, asterisk with single space indent.
* Final line: indented one space, as below.
*/

Variables
First character always $, second always a letter or underscore, subsequent characters a-z,A-Z,0-9 or underscore. Case sensitive.

Variable's data type selected and converted by PHP according to context.

Function variables have function scope. Global variables declared with keyword global. Static variables declared with static keyword. 'Super globals' provided by PHP as arrays are automatically available everywhere. List here:
http://www.php.net/manual/en/reserved.variables.php

Strings
Double-quoted strings can contain variables, which will be evaluated, and characters such as newline (\n), return (\r) and tab (\t). Single-quoted strings will output variables literally, require escaping of apostrophes, but can contain un-escaped double quotation marks.

Strings are concatenated with '.'
Where other data types are concatenated with strings, the result is a string.

Comparison
strcmp($s1, $s2) performs case sensitive string comparison. Returns 0 if $s1 and $s2 are same, nonzero if different.
strcasecmp($s1, $s2) performs (contrary to its name!) case insensitive comparison.

== compares two expressions. (0==FALSE) is true.
=== compares expressions and data type. (0===FALSE) is false.
Similarly, != compares expressions; compares expressions and data type.

Constants
Constant names do not begin with $ and by convention are capitalised. Can only be defined with the define("NAME", value) function, not by assignment. If a constant's name is stored in a variable or returned by a function, constant(NAME) must be used to retrieve its value. Constants are defined globally.

get_defined_constants() returns an array of program defined constants.

Combined assignment
Example: $num+=1. Also -=, *=, /= and .=, the last for string concatenation.

Autoincrement
Postincrement, postdecrement: $num++, $num--
Preincrement, predecrement: ++$num, --$num