Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to PHP (1) Background, Data Types, Control Structures & Functions.

Similar presentations


Presentation on theme: "Introduction to PHP (1) Background, Data Types, Control Structures & Functions."— Presentation transcript:

1 Introduction to PHP (1) Background, Data Types, Control Structures & Functions

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

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

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

5 Pre-amble (3) 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 Preprocessor’ 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 PHP version 5.2.4 current at UWE PHP Version 6 due for release since late 2010 but ??

6 Preamble (4) 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 Preamble (5) 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 + 3 )

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

10 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. <?php $cities[0] = “London”; $cities[1] = “Bath”; $cities[2] = “Bristol”; print (“I live in $cities[2]. \n”); ?> - 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. <?php $modules = array( “ISD”=>array( “Joe”, “Tim”, “Mary” ) “ISDP”=>array( “Bob”, “Tom”, “Sue” ) ); print ($modules[“ISD”][2]); ?>

11 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 http://www.slideshare.net/mgirouard/a-gentle-introduction-to-object-oriented-php/ o resources : are a data type that hold handles to external resources such as open files or database connections.

12 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)

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

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

15 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). ”); ?> Output? Note: if you leave out the index number, php will start at 0 and use consecutive integers thereafter.

16 <?php $teacher[] = “Prakash”; $teacher[] = “Paul”; $teacher[] = “Dan”; $teacher[] = “Chris”; $indexCount = count ($teacher); for ($index=0; $index < $indexCount; $index++) { print(“Teacher $index is $teacher[$index]. ”;) } ?> PHP Data Structures (2) example: counting and accessing values using a loop arrays (cont.) Output?

17 <?php //fill in some info $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. ”); } ?> Output? PHP Data Structures (3) arrays (cont.) Associative Arrays (Hashes in Perl, HashMaps in Java)

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

19 PHP Functions (1) : inbuilt function library (700+) - Basic tasks –String Handling –Mathematics – random numbers, trig functions.. –Regular Expressions –Date and time handling –File Input and Output - And more specific functions for- –Database interaction – - MySQL, Oracle, Postgres, Sybase, MSSQL.. –Encryption –Text translation –Spell-checking –Image creation –XML etc.etc.

20 PHP Functions (2) : user defined functions - Declaring a function - functions are declared using the function statement, a name and parenthesis () e.g function myfunction() {…..} - functions can accept any number of arguments and these are separated by commas inside the parenthesis e.g function myFunction(arg1, arg2) {…..} - the following simple function prints out any text passed to it as bold <?php function printBold($text){ print(" $text "); } print("This Line is not Bold \n"); printBold("This Line is Bold"); print(" \n"); print("This Line is not Bold \n"); ?>

21 - the return statement - at some point the function will finish and is ready to return control to the caller - execution then picks up directly after the point the function was called - it is possible to have multiple return points from a function (but this will reduce code readability) - if a return statement includes an expression, return(expression), the value of the expression will be passed back - example <?php function makeBold($text){ $text = " $text "; return($text); } print("This Line is not Bold \n"); print(makeBold("This Line is Bold"). " \n"); print("This Line is not Bold \n"); ?> PHP Functions (3) : user defined functions

22 - values and references - for most data types, return values are passed by value - for objects, discussed next week, return values are returned by reference - the following function creates a a new array of 10 random numbers between 1 and 100 and passes it back as a reference <?php function &getRandArray() { $a = array(); for($i=0; $i<10; $i++) { $a[] = rand(1,100); } return($a); } $myNewArray = &getRandArray(); ?> PHP Functions (4) : user defined functions

23 - scope (1) - scoping is way of avoiding clashes between variables in different functions - each code block belongs to a certain scope - variables within functions have local scope and are private to the function - variables outside a function have a global scope <?php $a = 1; /* global scope */ function test(){ echo $a; /* reference to local scope variable */ } test(); ?> The above example will output nothing because the $a inside the function has local scope PHP Functions (5) : user defined functions

24 - the global keyword can be used to access variables from the global scope within functions <?php $a = 1; $b = 2; function Sum(){ global $a, $b; $b = $a + $b; } Sum(); echo $b; ?> - The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function. PHP Functions (6) : user defined functions

25 - arguments - functions expect arguments to to be preceded by a dollar sign ($) and these are usually passed to the function as values - if an argument has a & sign in front - it is treated as a reference - the following example shows an argument passed as reference <?php function stripCommas(&$text){ $text = str_replace(",", "", $text); } $myNumber = "10,000"; stripCommas($myNumber); print($myNumber); ?> PHP Functions (7) : user defined functions

26 -default values - a function can use a default value in an argument using the = sign to precede the argument - consider the follwing example <?php function setName($FirstName = "John", $LastName = "Smith"){ return "Hello, $FirstName $LastName!\n"; } ?> - So, to greet someone called John Smith, you could just use this: setName(); - To greet someone called Tom Davies, you would use this: setName("Tom", "Davies"); - To greet someone called Tom Smith, you would use this: setName("Tom"); PHP Functions (8) : user defined functions

27 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

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

29 PHP Resources -php home : http://www.php.nethttp://www.php.net -learning PHP : php @ w3 schoolsphp @ w3 schools -code and examples : php extension & application library (pear) : http://pear.php.net/ http://pear.php.net/ resource index : http://php.resourceindex.com/http://php.resourceindex.com/ weberdev : http://www.weberdev.com/ArticlesSearch/Category/Begi nner+Guides http://www.weberdev.com/ArticlesSearch/Category/Begi nner+Guides phpexample : http://phpexamples.me/http://phpexamples.me/


Download ppt "Introduction to PHP (1) Background, Data Types, Control Structures & Functions."

Similar presentations


Ads by Google