Presentation is loading. Please wait.

Presentation is loading. Please wait.

UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 2 PHP (1) : Data Types, Control Structures, Data Structures, String Handling & Input/Output.

Similar presentations


Presentation on theme: "UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 2 PHP (1) : Data Types, Control Structures, Data Structures, String Handling & Input/Output."— Presentation transcript:

1 UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 2 PHP (1) : Data Types, Control Structures, Data Structures, String Handling & Input/Output

2 Pre-amble (1) Web 1.0 Basic web 1.0 architecture & communication

3 Pre-amble (2) http request/response cycle

4 Pre-amble (3) Web oriented 3-tier architecture PHP script Remote services Web Server (Apache, IIS) Browser (IE, Chrome, FireFox, Opera) Desktop (PC or MAC) Database Server SQLHTTP HTML Web Service tables DHTML vision touch voice

5 PHP Origins Originally created by Rasmus Lerdorf (born Greenland, educated in Canada) around 1995Rasmus Lerdorf PHP originally abbreviated as ‘Personal Home Pages’, now known as ‘PHP Hypertext Pre-processor’ Other key developers: Zeev Surashi and Andi Gutmans (Israel) responsible for PHP a complete re-write of the original PHP/F1 engine (1997) PHP is Open Source software First version PHP/FI released 1995 PHP 5.0 released July 2004 Current stable version is (as of August 2012) PHP version current at UWE PHP Version 6 due for release since late 2010 but ??

6 PHP as a scripting language o A scripting language is: –often evolved not designed –cross-platform since interpreter is easy to port –designed to support a specific task – PHP Web support –un-typed variables (but values are typed) –implicit variable declaration –implicit type conversion –stored only as script files –compiled on demand –may run on the server (PHP, Perl) or the client (Javascript) o What are the potential differences in programming using an interpreted scripting language like PHP in place of a compiled language (e.g. Java in JSP,.NET)?

7 o Free format - white space is ignored o Statements are terminated by semi-colon ; o Statements grouped by { … } o Comments begin with // or a set of comments /* */ o Assignment is ‘=’: $a=6 o Relational operators are, == ( not a single equal) o Control structures include if (cond) {..} else { }, while (cond) {.. }, for(startcond; increment; endcond) { } o Arrays are accessed with [ ] - $x[4] is the 5th element of the array $x – indexes start at 0 o Associative Arrays (hash array in Perl, dictionary in Java) are accessed in the same way: $y["fred"] o Functions are called with the name followed by arguments in a fixed order enclosed in ( ) : substr("fred",0,2) o Case sensitive - $fred is a different variable to $FRED C-like language

8 PHP Scripts o every PHP script is a collection of one or more statements; these statements appear as a collection of names, numbers and special symbols; o individual statements are terminated by a semicolon (;) and blocks of statements are contained within curly brackets ({.. }); o statements can be simple (e.g. print or echo) while others can be grouped statements (e.g. the if {.. } elseif {.. } else {.. } block) o PHP can use literal values such as numbers and blocks of text (e.g. 9 or "some text") or give names to specific expressions (e.g. variables, functions or classes) o operators are used to join values, usually one value to the left of the operator and one to the right (e.g )

9 PHP Simple Example Welcome to PHP, ! Simple PHP script example single line comment, use # or // variable ($name) with value assignment (‘Popeye’) scripting delimiters call to built-in ‘echo()’ function view scriptview script run scriptrun script

10 Data Types (1) o PHP has eight different data types – 5 basic and 2 composite types and 1 resource type o The 5 basic data types are: -integers : whole numbers in the range -2,147,483,648 to +2,147,483,647 on 32-bit architecture. Can be octal (prefixed by 0), decimal and hexadecimal (prefixed by 0x) -floating-point : real or doubles (decimal), can be written using base 10 notation (e.g == 3.9e3) -strings : sequence of characters contained by single (‘..’) or double ("..") quotes. Within double quotes variables are replaced by their values (interpolated). Escape sequences are used to include special characters within double quoted strings (e.g. \" to include a double quote and \\ to include a backslash) -booleans : the boolean data type evaluates to either true or false (e.g. $a == $b will evaluate to true if both variables contain the same value, false otherwise -null : a special data type that stands for a lack of value. Often used to initialize or reset variables.

11 Data Types (2) o arrays : are a composite data type that collect values into a list. The values of the array elements can be text, a number or even another array. Arrays can be from 1 to any number of dimensions. - arrays are referenced using square [.. ] brackets. - an array can be indexed using a string value for the index (called associative array or hash) and are useful in situations where there is a need to collect different types of data into one array. (e.g. $userInfo ["name"] = "Kevin"; ) - array elements containing other arrays are used to build multi-dimensional arrays. array( "Joe", "Tim", "Mary" ) "ISDP"=>array( "Bob", "Tom", "Sue" ) ); print ($modules["ISD"][2]); ?>

12 Data Types (3) o objects : are another composite data type fully supported by php. - php supports standard object-oriented (OO) methodologies and techniques such as inheritance - the ability to derive new classes from existing ones and inherit or override their attributes and methods. encapsulation - the ability to hide data from users of the class (the public, protected and private keywords.) special methods - for instance, code that is automatically run when a object is created (constructor) or destroyed (destructor). polymorphism – overloading a function so that a function call will behave differently when passed variables of different type. - a good introducton to OO programming using php can be found at o resources : are a data type that hold handles to external resources such as open files or database connections.

13 Control statements are a means of executing blocks of code depending on one or more conditions. if (expression) {..} : the simple if statement takes the following form – if (expression) { this block gets executed if the expression evaluates to true } if (expression) {..} elseif (expression) {..} else {..} : the compound if statement takes the following form – if (expression1) { this block gets executed if expression1 is true } elseif (expression2) { this block gets executed if expression1 is false and expression2 is true } else { this block gets executed if both expression1 and expression2 are false } ? operator : acts as a shortened version of the if {..} statement. It takes the followng form - conditional expression ? true expression : false expression; Control Structures (1)

14 Control Structures (2) switch (expression) {case expression.. case expression.. default} : similar to the if.. elseif.. else structure where a single expression is compared to a set of possible values and if a match is made, the block following the match is executed. The break statement can be used to jump out of a switch structure. A default expression can be used to execute code if none of the expressions evaluates to true. o Loops – allow for the repetition of blocks of code until a condition is met. while (expression) {..} : when first reached the expression is evaluated and if true the block of code following the expression is executed, otherwise the block is skipped. The break statement can be used to break out of a while block. The continue statement can be used to return control to the beginning of the block. do {..} while (expression) : is a way of delaying the decision to execute a code block until the end. for (initialization; continue; increment) {..} : used to carry out a block a code a specific number of times. foreach (array as key=>value) {..} : provides a formalized method for iterating over arrays.

15 Control Structures (3) exit, die and return : the exit statement is used to stop execution – it is useful when an error occurs and it could be harmful to continue execution; the die statement is similar to exit but can be followed by an expression which is sent to the browser just before the script is aborted, for instance $fp = fopen("somefile.txt", "r") OR die("Could not open file"); the return statement can be used within functions (see following section) but can also be used with the include statement. If used within a script, it stops execution within the current script and returns control to the script that made a call to include. That is, when a include is used, the included script may return prematurely.

16 PHP Data Structures (1) arrays - arrays collect values into lists - individual items (elements) are accessed using an index which can be an integer or a string - you can build arbitrarily complex data structures using arrays within arrays, that is, a value within an array can hold another array (multidimensional array) single dimension arrays - use square brackets [ ] to refer to an element - arrays are treated like normal variables – you can create it at the point of use without having to declare anything first. example: referencing array elements Output? Note: if you leave out the index number, php will start at 0 and use consecutive integers thereafter.

17 PHP Data Structures (2) example: counting and accessing values using a loop arrays (cont.) run script

18 $value) { print ("$key is $value "); } ?> PHP Data Structures (3) arrays (cont.) Associative Arrays (Hashes in Perl, HashMaps in Java) run script

19 String Handling o String literals (constants) enclosed in double quotes " " or single quotes ‘ ’ o Within "", variables are replaced by their value: – called variable interpolation. "My name is $name, I think" o Within single quoted strings, interpolation doesn’t occur o Strings are concatenated (joined end to end) with the dot operator "key"."board" == "keyboard" o Standard functions exist: strlen(), substr() etc o Values of other types can be easily converted to and from strings – numbers implicitly converted to strings in a string context. o Regular expressions be used for complex pattern matching.

20 Input / Output & Disk Access (1) o Reading and Writing to Files Communicating with files follows the pattern of opening a stream to a file, reading from or writing to it, and then closing the stream. fopen(..) : the fopen function opens a file for reading or writing. The function expects the name of a file and a mode e.g. fopen ("c:/temp/myfile.txt", "r"); which opens a file called myfile.txt in the directory "c:/temp" in the "read" mode File read/write modes : rreading only wwrite only, create if necessary, discard previous content aappend to file, create if necessary, start writing at end r+reading and writing w+reading & writing, create if necessary, discard previous content a+reading & writing, create if necessary, start writing at end

21 Input / Output & Disk Access (2) fclose (resource file) : used to close a file. feof (resource file) : as a file is read, php keeps a pointer to the last place in the file read; the feof function returns true if the end of file is reached. fgetcsv(resource file, integer length, string separator) : used for reading comma-separated data from a file. The optional separator argument specifies the character to separate fileds’ If left out, a comma is used. fgets(resource file, integer length) : returns a string that reads from a file. It will attempt to read as many characters – 1 as specified by the length value. A linebreak character is treated as a stopping point, as is the end of the file. fwrite(resource file, string data, integer length) : writes a string to a file. The length argument is optional and sets the number of bytes to write.

22 the exit() and die() functions o both the exit() and die() statements terminate the execution of a script. The two statements are equivalent. o a message can be output as the script is terminated e.g. $filename = '/path/to/data-file'; $file = fopen($filename, 'r') or exit("unable to open file ($filename)");

23 PHP Books Intermediate : Nixon, Robin : Learning PHP, MySQL, JavaScript and CSS: A Step-by- Step Guide to Creating Dynamic Websites : O'Reilly Media, 2 nd ed., 2012Learning PHP, MySQL, JavaScript and CSS: A Step-by- Step Guide to Creating Dynamic Websites Ullman, Larry : PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide : Peachpit Press, 4 th ed., 2011PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide McLaughlin, Brett : PHP & MySQL: The Missing Manual : Pogue Press, 2011PHP & MySQL: The Missing Manual Advanced : Zandstra, Matt : PHP Objects, Patterns and Practice, Apress, 3rd ed., 2010PHP Objects, Patterns and Practice Gogala, Mladen : Pro PHP Programming : Apress, 2011Pro PHP Programming Saray, Aaron : Professional PHP Design Patterns : Wrox, 2009Professional PHP Design Patterns

24 On-line Resources -php home : -learning PHP : w3 w3 schools -code and examples : php extension & application library (pear) : resource index : weberdev : nner+Guides nner+Guides phpexample :


Download ppt "UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 2 PHP (1) : Data Types, Control Structures, Data Structures, String Handling & Input/Output."

Similar presentations


Ads by Google