- 快召唤伙伴们来围观吧
- 微博 QQ QQ空间 贴吧
- 文档嵌入链接
- 复制
- 微信扫一扫分享
- 已成功复制到剪贴板
Introduction to PHP
展开查看详情
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 Database Server SQL HTTP HTML Web Service tables DHTML vision touch voice
5 .PHP Origins Originally created by Rasmus Lerdorf (born Greenland, educated in Canada) around 1995 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 3.0 - 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 5.4.6 (as of August 2012) PHP version 5.2.4 current at UWE PHP Version 6 due for release since late 2010 but ??
6 .PHP as a scripting language 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 ) 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 .Free format - white space is ignored Statements are terminated by semi-colon ; Statements grouped by { … } Comments begin with // or a set of comments /* */ Assignment is ‘=’: $a=6 Relational operators are ,< , > == ( not a single equal) Control structures include if ( cond ) {..} else { }, while ( cond ) { .. } , for( startcond ; increment; endcond ) { } Arrays are accessed with [ ] - $x[4] is the 5th element of the array $x – indexes start at 0 Associative Arrays (hash array in Perl, dictionary in Java) are accessed in the same way: $y[" fred "] Functions are called with the name followed by arguments in a fixed order enclosed in ( ) : substr ("fred",0,2) Case sensitive - $ fred is a different variable to $FRED C-like language
8 .PHP Scripts every PHP script is a collection of one or more statements ; these statements appear as a collection of names, numbers and special symbols; individual statements are terminated by a semicolon (;) and blocks of statements are contained within curly brackets ({ .. }); statements can be simple (e.g. print or echo ) while others can be grouped statements (e.g. the if { .. } elseif { .. } else { .. } block) 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) operators are used to join values , usually one value to the left of the operator and one to the right (e.g. 9 + 3 )
9 .<! DOCTYPE html> <html> <? php # declare a variable & assign it a value $name = "Popeye"; ?> <head> <title> PHP Simple Example </title> </head> <body> <p> Welcome to PHP, <? php echo ("$name"); ?> ! </p> </body> </html> Simple PHP script example s ingle line comment, use # or // v ariable ($name) with value assignment (‘Popeye’) s cripting delimiters c all to built-in ‘echo()’ function v iew script run script
10 .Data Types (1) PHP has eight different data types – 5 basic and 2 composite types and 1 resource type 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. 3900 == 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) 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. <? php $cities[0] = "London"; $cities[1] = "Bath"; $cities[2] = "Bristol"; print ("I live in $cities[2].< br />
12 .Data Types (3) 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 – o verloading 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 http://www.slideshare.net/mgirouard/a-gentle-introduction-to-object-oriented-php/ 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. 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 <? php $teacher[0] = " Prakash "; $teacher[1] = "Paul"; $teacher[2] = "Dan"; $teacher[3] = "Chris"; echo ("$teacher[3] teaches DSA).< br />"); ?> Output? Note: if you leave out the index number, php will start at 0 and use consecutive integers thereafter.
17 .<? php $teacher[] = " Prakash "; $teacher[] = "Paul"; $teacher[] = "Dan"; $teacher[] = "Chris"; $ indexCount = count ($teacher); for ($index=0; $index < $ indexCount ; $index++) { print ("Teacher $index is $teacher[$index]. < br />"); } ?> PHP Data Structures (2) example: counting and accessing values using a loop arrays (cont.) r un script
18 .<? php //create hash with data $user["Name"] = "Leon Trotsky"; $user["Location"] = " Coyoacan , Mexico City"; $user["Occupation"] = "Revolutionary"; //loop over the values foreach ($user as $key=>$value) { print ("$ key is $value< br />"); } ?> PHP Data Structures (3) arrays (cont.) Associative Arrays (Hashes in Perl, HashMaps in Java) r un script
19 .String Handling String literals (constants) enclosed in double quotes " " or single quotes ‘ ’ Within "", variables are replaced by their value: – called variable interpolation . "My name is $name, I think" Within single quoted strings, interpolation doesn’t occur Strings are concatenated (joined end to end) with the dot operator " key"."board " == "keyboard" Standard functions exist: strlen (), substr () etc Values of other types can be easily converted to and from strings – numbers implicitly converted to strings in a string context. Regular expressions be used for complex pattern matching.
20 .Input / Output & Disk Access (1) 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 : r reading only w write only, create if necessary, discard previous content a append 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 both the exit() and die() statements terminate the execution of a script. The two statements are equivalent. 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 .the exit() and die() functions both the exit() and die() statements terminate the execution of a script. The two statements are equivalent. 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)");
24 .On-line Resources - php home : http://www.php.net learning PHP : php @ w3 schools code and examples : php extension & application library (pear) : http://pear.php.net/ resource index : http://php.resourceindex.com/ weberdev : http://www.weberdev.com/ArticlesSearch/Category/Beginner+Guides phpexample : http://phpexamples.me/