Princeton University COS 333: Advanced Programming Techniques A Subset of PHP Program Structure <?php // Print "hello, world\n" echo "hello, world\n";?> ----------------------------------------------------------------------------------- <?php function sqr($i) return $i * $i; echo sqr(5). "\n";?> ----------------------------------------------------------------------------------- Typically embedded in a HTML document. Including include "file.php"; include_once "file.php"; require "file.php"; require_once "file.php"; Exec Continues File Included Upon Failure? Only Once? include y n include_once y y require n n require_once n y Building and Running php file.php Terminal I/O Reading from stdin: ivaluesread = fscanf(stdin, "%d %lf", $i, $d); Writing to stdout: icharswritten = printf("%d %f", $i, $d); Page 1 of 6
Writing to stderr: icharswritten = fprintf(stderr, "%d %f", $i, $d); Keywords and, or, xor, FILE, exception, LINE, array(), as, break, case, class, const, continue, declare, default, die(), do, echo(), else, elseif, empty(), enddeclare, endfor, endforeach, endif, endswitch, endwhile, eval(), exit(), extends, for, foreach, function, global, if, include(), include_once(), isset(), list(), new, print(), require(), require_once(), return(), static, switch, unset(), use, var, while, FUNCTION, CLASS, METHOD, final, php_user_filter, interface, implements, instanceof, public, private, protected, abstract, clone, try, catch, throw, cfunction, this, final, NAMESPACE, namespace, goto, DIR Primitive Data Types Integer: 1, 12345, 01, 012345, 0x1, 0x1DB5 Floating point number: 0.0, 1.23, 1.23e4 Interpreted string: "hi" Uninterpreted (raw) string: 'hi' Boolean: true, false (case insensitive) Null object: null (case insensitive) Conversions: (int), (integer): (bool), (boolean): (float), (double), (real): (string): (array): (class): (unset): cast to integer cast to boolean cast to float cast to string cast to array cast to class cast to NULL No declaration statements; variables are created when first assigned a value Operators non-associative clone, new (1) clone and new left [] (2) array() non-associative ++ -- (3) increment/decrement right ~ - (4) bitwise not, negation right (int) (float) (string) (4) typecast right (array) (object) (bool) @ (4) typecast non-associative instanceof (5) type check right! (6) logical left * / % (7) arithmetic left + -. (8) arithmetic and string left << >> (9) bitwise non-associative < <= > >= <> (10) comparison non-associative ==!= ===!== (11) comparison left & (12) bitwise and references left ^ (13) bitwise left (14) bitwise left && (15) logical left (16) logical left? : (17) conditional expression right = += -= *= /=.= %= (18) assignment Page 2 of 6
right &= = ^= <<= >>= => (18) assignment left and (19) logical left xor (20) logical left or (21) logical left, (22) many uses Statements Expression statement: expr; Echo statement: echo expr, expr,...; Compound statement: statement; statement;... Selection statements: if (booleanexpr) statement else statement; Note: false, 0, null, '', "", and array() all indicate logical FALSE; any other value indicates logical TRUE switch (expr) case (value1): statement;...; break; case (value2): statement;...; break;... default: statement;...; Iteration statements: while (booleanexpr) statement; do statement while (expr); for (initexpr; booleanexpr; increxpr) statement; Note: false, 0, null, '', "", and array() all indicate logical FALSE; any other value indicates logical TRUE foreach ($array as $element) statement; foreach ($associativearray as $key => $value) statement; break; continue; Return statement: Page 3 of 6
Function call: return; return expr; f(expr,...); Default is call-by-value. & preceding a formal parameter indicates call-by-reference. Exception handling: try... catch (Exception $e)... $e->getmessage()... throw new Exception("Description"); Classes, Objects, and Object References <?php class MyClass private $i; public function construct($i) $this->i = $i; public function get() return $this->i; public function set($i) $this->i = $i; function main() $obj1 = new MyClass(5); $obj1->set(10); echo $obj1->get(). "\n"; print_r($obj1);?> main(); Data Structures Arrays $a = array(1, 2, "three"); $a[] = "four"; // Appends. echo $a[0]; Associative Arrays $aa = array("john" => "rhythm guitar", "Paul" => "bass guitar"); $aa["george"] = "lead guitar"; $aa["ringo"] = "drums"; echo $aa["paul"]; Page 4 of 6
Functions on Arrays is_array(), count(), sort(), shuffle(), explode(), extract(), compact(), reset(), end() An array is not an object. Often must use call-by-reference when passing an array to a function. Strings function fill1($a) $a[] = 5; $a[] = 6; $a[] = 7; function fill2(&$a) $a[] = 5; $a[] = 6; $a[] = 7; $a = array(); fill1($a); // a is unaffected. fill2($a); // a is affected. Functions on Strings Files strlen(), strpos(), strtolower(), strtoupper(), chr(), ord(), explode(), implode(), ltrim(), rtrim(), trim(), substr(), str_replace(), ucwords() fopen(), fgets(), fscanf(), fprintf(), fclose() as in C $bool = file_exists($file); STDIN, STDOUT, and STDERR are predefined. Command-Line Arguments $argc is the argument count $argv is a list $argv[0] is the name of the program... if ($argc!= 3) echo "Usage: $argv[0] arg1 arg2"; exit(1); Superglobal Variables When run within a web server: $GLOBALS $_SERVER $_GET $_POST $_FILES $_COOKIE $_SESSION $_REQUEST $_ENV All variables Headers, paths, script locations, etc. Data passed to the script via the HTTP GET method Data passed to the script via the HTTP POST method Data uploaded to the script via the HTTP POST method Data passed to the script via HTTP cookies Session data Data from the browser, by default $_GET, $_POST, and $_COOKIE Data passed to the script via environment variables Page 5 of 6
Etc. We'll cover other features of PHP throughout the course as necessary. Copyright 2011 by Robert M. Dondero, Jr. Page 6 of 6