1 PHP Introduction Chapter 1. Syntax and language constructs
PHP’s Type Strength PHP is a dynamically typed language (a.k.a. weakly typed language): ○ The type of a variable is not / cannot be (!) declared when you create a new variable ○ The type of a variable is automatically determined by the value assigned to it ○ The type of a variable can change throughout the program according to what is stored in it at any given time $totalqty = 0; // integer $totalamount = 0.00; // float $totalamount = ‘Hello’; // string 2
PHP’s Type Casting You can force a data type by type casting ○ Syntax: put target type in parentheses in front of variable/expression you want to cast (similar to Java): $totalqty = 0; $totalamount = (float) $totalqty; // $totalamount variable will be of type float and // cast variable doesn’t change types! Built-in functions are also available to test and set type (see later) 3
Constants Use the define() function to create a constant define("CONSTANT_NAME", value); Constant names: Do not begin with a dollar sign (!) It is common practice to use all uppercase letters for constant names Are case sensitive by default (this can be changed, but not recommended!) The value you pass to the define() function can only be a scalar value: a string, integer, float, or boolean value define(“VOTING_AGE”, 18); echo “ The legal voting age is ”, VOTING_AGE, " "; Note no $ sign precedes constant names in expressions! A constant’s name cannot be used as variable names within the quotation signs surrounding a string! A list of predefined vars and constants can be obtained calling phpinfo() 4
Variables’ Scope I. PHP superglobals: 5
Variables’ Scope - 6 basic scope rules I. Built-in superglobal or autoglobal variables are visible everywhere (=globally) within a script, both inside and outside functions. PHP includes various autoglobals or superglobals, which are predefined global arrays. Autoglobals contain client, server, and environment information that you can use in your scripts. Autoglobals are associative arrays – arrays whose elements are referred to with an alphanumeric key instead of an index number. 6
PHP Operators Arithmetic operators: Binary operators +, -, *, /, % Usually applied to integers or doubles String operands are converted to numbers: starting at the beginning of the string up to 1 st non-valid character; if no valid characters, the value of the string will be 0. Unary operators +, - String operators:. – the string concatenation operator $s1 = “Bob’s ”; $s2 = “Auto Parts”; $result = $s1. $s2; // result now contains the string “Bob’s Auto Parts” 7
Operators Crash_Course_Examples/operators.php Crash_Course_Examples/operators.php ples/PHP_Crash_Course/operators_php.pdf ples/PHP_Crash_Course/operators_php.pdf
PHP Operators Assignment operators: Basic assignment operator = The value of an assignment expression lhs_operand = rhs_expression is the value that is assigned to lhs_operand = associates from right to left expressions like the following one are correct: $a = $b = 6 + $c = 9; // $c is now 9, $a and $b are 15 // can also be written as $a = $b = 6 + ($c = 9); Combined assignment operators: +=, -=, *=, /=, %=,.= $a += 5;is equivalent to $a = $a + 5; 9
PHP Operators Assignment operators: Pre- and Post-Increment and Decrement: ++, -- All 4 operators modify the operand and the value of the expression is the old value (post) or the new value (pre) of the operand (like in Java). Reference operator: & $a = 5; $b = $a; a copy of the value in $a is made and stored in $b, elsewhere in memory $b = &$a; $b is an alias for the same memory location which is referred to as $a = $a and $b are associated with / name the same memory location $a = 7; // both $a and $b are now 7 unset($b) breaks the link between name $b and the memory location storing 7 → $b is now undefined 10
PHP Operators Comparison operators: ==equals ===identical (if operands are equal and of the same type) !=not equal <>not equal !==not identical < > <= >= string comp_op integer → string is converted to a number 0==‘0’ → true 0 === ‘0’ → false string comp_op string → compared as numbers if they are numerical strings… 11
PHP Operators Logical operators (combine the results of logical conditions): !NOT &&AND ||OR andAND (but lower precedence than &&) orOR (but lower precedence than ||) xorEXCLUSIVE OR ($a xor $b is true when exactly one of $a and $b is true) The execution operator ``(= a pair of backticks, not quotes!) PHP tries to execute the content between `` as a command at the server’s command line. The value of the expression is the output of that command. Example: $out = `dir`; // on a Win server, the list of files/directories in current directory = where the script is echo “ $out ”; 12
PHP Operators - Precedence & Associativity Precedence = order in which operations in an expression are evaluated Associativity = order in which operators of equal precedence are evaluated 13 $a=5; $b=4; ? The value of the following expression? $b + ++$a/2 + 3 == 10
Using Variable Functions Testing and setting variable types: string gettype(mixed variable) Returns one of the strings: “bool”, “int”, “double”, “string”, “array”, “object”, “resource”, “NULL”, or “unknown type”. “Mixed” – is a pseudo-type / signifies that variables of many (or any) data types are accepted as arguments; or function is “oveloaded” bool settype(mixed variable, string type) Sets the type of “variable” to the new type passed as a second argument. “Type” can be “bool”, “int”, “double”, “string”, “array”, “object”, “resource”, “NULL”. $a = 56; echo gettype($a).’ ’;// displays int settype($a, ‘double’); echo gettype($a).’ ’;// displays double 14
Using Variable Functions Specific type-testing functions, return true of false is_array(variable) is_double(variable)is_float(variable)is_real(variable) is_long(variable)is_int(variable)is_integer(variable) is_string(variable) is_bool(variable) is_object(variable) is_resource(variable) is_null(variable) is_scalar(variable) – checks whether variable is an integer, boolean, string or float is_numeric(variable) – checks whether variable is any kind of number or a numeric string is_callable(variable) – checks whether variable is the name of a valid function 15
Using Variable Functions Testing variable status: bool isset(mixed variable1 [, mixed variable2 …] ) Returns true if all variables passed to the function exist and false otherwise void unset(mixed variable1 [, mixed variable2, …]) Gets rid of the variable(s) it is passed bool empty(mixed variable) Checks if variable exists and has a nonempty, nonzero value These functions are very useful for checking (server-side) if the user filled out the appropriate fields in the form; example: echo isset($tireqty); // always true for a textbox field echo empty($tireqty); // depends on user input, false if form field is empty 16
PHP Conditionals if (condition) statement or code_block where code_block = { statement(s) } if (condition) statement or code_block else statement or code_block NOTE: when writing a cascading set of if-else statements “else if” can be also written “elseif” Conditional operator: condition ? value_if_true : value_if_false switch Same syntax as Java; control expression and case labels can evaluate to integer, string or float Must use break to end execution after a matching case 17
PHP Conditionals - Example HTML form contains the following select list: I'm a regular customer TV advertising … Equivalent if-else and switch statements for processing form data for the select form field: $find = $_POST["find"]; if ($find == "a") echo " Regular customer. "; elseif ($find == "b") echo " Customer referred by TV advertising. "; … switch($find) { case "a": echo " Regular customer. "; break; … } 18
PHP Conditionals - Example Crash_Course_Examples/orderform_3.h tml Crash_Course_Examples/orderform_3.h tml ples/PHP_Crash_Course/processorder_ 3_php.pdf ples/PHP_Crash_Course/processorder_ 3_php.pdf
PHP Loop Statements while ( condition ) // same semantics as in Java statement or code_block Example - generate a shipping cost table, if prices are proportional to the distance: Distance Cost <?php $distance = 50; while ($distance <= 250 ) { echo " \n $distance \n"; echo " ". $distance/10." \n \n"; $distance += 50; } ?> 20
PHP Loop Statements Crash_Course_Examples/freight.php Crash_Course_Examples/freight.php ples/PHP_Crash_Course/freight_php.pd f ples/PHP_Crash_Course/freight_php.pd f
PHP Loop Statements do statement or code_block while ( condition ); // same semantics as in Java for (initial-action; loop-continuation-condition; action-after-each-iteration) statement or code_block // same semantics as in Java Interesting example – combine variable variables with a for loop to iterate through and process a series of form fields with repetitive names, such as name1, name2, name3 etc: for ($i=1; $i<=$numfields; $i++) { $temp = “name$i”; // $i is interpolated! echo $$temp. “ ”; } 22
Alternative Control Structure Syntax control_structure (expression_or_condition) : statements; special_keyword; The alternative syntax can be used for: statement special_keyword is: if endif switch endswitch while endwhile for endfor if ($totalqty == 0) : echo " You didn’t order anything on the previous page! "; exit; endif; 23