1 / 23

PHP Introduction

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

Download Presentation

PHP Introduction

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PHP Introduction Chapter 1. Syntax and language constructs

  2. 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

  3. 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)

  4. 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 “<p>The legal voting age is ”, VOTING_AGE,"</p>"; • 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! • Alist of predefined vars and constants can be obtained calling phpinfo()

  5. Variables’ Scope • PHP superglobals:

  6. Variables’ Scope - 6 basic scope rules • Built-in superglobalor autoglobalvariables 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.

  7. 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 1st 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”

  8. Operators • http://cscdb.nku.edu/csc301/frank/PHP_Crash_Course_Examples/operators.php • http://www.nku.edu/~frank/csc301/Examples/PHP_Crash_Course/operators_php.pdf

  9. 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; // $cis now 9, $a and $b are 15 // canalso be written as $a = $b = 6 + ($c = 9); • Combined assignment operators: +=, -=, *=, /=, %=, .= • $a += 5; is equivalent to $a = $a +5;

  10. 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

  11. 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…

  12. PHP Operators • Logical operators (combine the results of logical conditions): • ! NOT && AND || OR and AND (but lower precedence than &&) or OR (but lower precedence than ||) xor EXCLUSIVE 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 “<pre> $out </pre>”;

  13. PHP Operators - Precedence & Associativity • Precedence =order in which operations in an expression are evaluated • Associativity =order in which operators of equal precedence are evaluated $a=5; $b=4; ? The value of the following expression? $b + ++$a/2 + 3 == 10

  14. 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).’<br/>’; // displays int settype($a, ‘double’); echo gettype($a).’<br/>’; // displays double

  15. 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

  16. 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

  17. 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

  18. PHP Conditionals - Example • HTML form contains the following select list: <select name="find"> <option value="a">I'm a regular customer</option> <option value="b">TV advertising</option> … </select> • Equivalent if-else and switch statements for processing form data for the select form field: • $find = $_POST["find"]; • if ($find == "a") echo "<p>Regular customer.</p>"; elseif ($find == "b") echo "<p>Customer referred by TV advertising.</p>"; … • switch($find) { case "a": echo "<p>Regular customer.</p>"; break; … }

  19. PHP Conditionals - Example • http://cscdb.nku.edu/csc301/frank/PHP_Crash_Course_Examples/orderform_3.html • http://www.nku.edu/~frank/csc301/Examples/PHP_Crash_Course/processorder_3_php.pdf

  20. 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: <table border="0" cellpadding="3"> <tr> <td class="header" align="center">Distance</td> <td class="header" align="center">Cost</td> </tr> <?php $distance = 50; while ($distance <= 250 ) { echo "<tr>\n <td align = 'right'>$distance</td>\n"; echo "<td align = 'right'>". $distance/10 ."</td>\n</tr>\n"; $distance += 50; } ?> </table>

  21. PHP Loop Statements • http://cscdb.nku.edu/csc301/frank/PHP_Crash_Course_Examples/freight.php • http://www.nku.edu/~frank/csc301/Examples/PHP_Crash_Course/freight_php.pdf

  22. 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 . “<br />”; }

  23. 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 "<p>You didn’t order anything on the previous page!</p>"; exit; endif;

More Related