Вы находитесь на странице: 1из 255

PHP-Basics

Copyright IBM Corporation 2012

Requesting a Static HTML Document


HTTP Request
GET /index.html HTTP/1.0 User-Agent: Mozilla/4.51 [en]... Host: sirah.csit.fsu.edu:8080 Accept: image/gif, ..., */* ...

Server

HTTP/1.1 200 OK Content-type: text/html <html> <head>...</head> <body> ... </html>

<html> <head></head> <body>

</html>

Static HTML files

Client

HTTP Response

2
Copyright IBM Corporation 2012

Dynamic Web pages


Applications executed by the server at run-time to process client input or generate document in response to client request Generating dynamic Web pages requires programming

Copyright IBM Corporation 2012

Dynamic Generation of HTML


HTTP Request
GET /hello.pl?who=bryan HTTP/1.0 User-Agent: Mozilla/4.51 [en]... Host: sirah.csit.fsu.edu:8080 Accept: image/gif, ..., */* ...
#!/usr/bin/perl $name = param(who) ; print Content-type: text/html\n\n ; print <html><body>Hello $name!</body></html>\n ;

Server

HTTP/1.1 200 OK Content-type: text/html <html> <body> Hello bryan! </body></html>

Script, or method

Client

HTTP Response

4
Copyright IBM Corporation 2012

Scripts: Server-Side VS ClientSide


Server-side
the first type possible on the Web action occurs at the server

Client-side
generally easier to implement may be prepared and implemented offline action occurs on the client side (browser)

Copyright IBM Corporation 2012

Client-Side Scripting
Client side scripts are embedded inside HTML document. They are interpreted by browser. When Web browser encounters a script, it calls a scripting interpreter, which parses and deciphers the scripting code. Provide response to questions and queries without interventions from the server Validate user data Calculate expressions Link to other applications

Copyright IBM Corporation 2012

What is PHP?
PHP == Hypertext Preprocessor Open-source, server-side scripting language Used to generate dynamic web-pages PHP scripts reside between reserved PHP tags This allows the programmer to embed PHP scripts within HTML pages

Copyright IBM Corporation 2012

What is PHP (contd)


Interpreted language, scripts are parsed at runtime rather than compiled beforehand Executed on the server-side Source-code not visible by client View Source in browsers does not display the PHP code Various built-in functions allow for fast development Compatible with many popular databases
Copyright IBM Corporation 2012

PHP's Place in the Web World


PHP is a programming language that's used mostly for building web sites.
Instead of a PHP program running on a desktop computer for the use of one person, it typically runs on a web server and is accessed by lots of people using web browsers on their own computers. This section explains how PHP fits into the interaction between a web browser and a web server.
Copyright IBM Corporation 2012

PHP's Place in the Web World


When you sit down at your computer and pull up a web page using a browser such as Internet Explorer or Mozilla, you cause a little conversation to happen over the Internet between your computer and another computer.

Copyright IBM Corporation 2012

PHP's Place in the Web World


Here's what's happening in the numbered steps of the diagram:
You type www.example.com/catalog.html into the location bar of Internet Explorer. Internet Explorer sends a message over the Internet to the computer named www.example.com asking for the/catalog.html page.

Copyright IBM Corporation 2012

Apache, a program running on the example.com computer,gets the message and reads the catalog.html file from the disk drive.

PHP's Place in the Web World


Apache sends the contents of the file back to your computer over the Internet as a response to Internet Explorer's request. Internet Explorer displays the page on the screen, following the instructions of the HTML tags in the page.
Every time a browser asks for example.com/catalog.html, the web server sends back the contents of the samecatalog.html file. The only time the response from the web server changes is if someone edits the file on the server
Copyright IBM Corporation 2012

PHP's Place in the Web World


Here's what's happening in the numbered steps of the PHP-enabled conversation: You type example.com/catalog/yak.php into the location bar of Internet Explorer. Internet Explorer sends a message over the Internet to the computer named example.com asking for the /catalog/yak.php page. Apache, a program running on the example.com computer, gets the message and asks the PHP interpreter,another program running on the example.com computer, "What does /catalog/yak.php look like?"
Copyright IBM Corporation 2012

PHP's Place in the Web World


The PHP interpreter runs the commands in yak.php, possibly exchanging data with a database program such as MySQL. The PHP interpreter takes the yak.php program output and sends it back to Apache as an answer to "What does/catalog/yak.php look like?"
Apache sends the page contents it got from the PHP interpreter back to your computer over the Internet in response to Internet Explorer's request.
Copyright IBM Corporation 2012

PHP Is Free (as in Money)


You don't have to pay anyone to use PHP.
Whether you run the PHP interpreter on a beat-up 10-year-old PC in your basement or in a room full of million-dollar "enterprise-class" servers, there are no licensing fees, support fees,maintenance fees, upgrade fees, or any other kind of charge.

Copyright IBM Corporation 2012

PHP Is Free (as in Speech)


As an open source project, PHP makes its innards available for anyone to inspect.
If it doesn't do what you want, or you're just curious about why a feature works the way it does.you can poke around in the guts of the PHP interpreter (written inthe C programming language) to see what's what. Even if you don't have the technical expertise to do that, you can get someone who does to do the investigating for you.
Copyright IBM Corporation 2012

PHP Is Cross-Platform
You can use PHP with a web server computer that runs Windows, Mac OS X, Linux, Solaris, and many other versions of Unix. if you switch web server operating systems, you generally don't have to change any of your PHP programs.
Just copy them from your Windows server to your Unix server, and they will still work.

Copyright IBM Corporation 2012

PHP Is Widely Used


As of March 2004, PHP is installed on more than 15 million different web sites, from countless tiny personal home pages to giants like Yahoo!.
There are many books, magazines, and web sites devoted to teaching PHP and exploring what you can do with it. There are companies that provide support and training for PHP.
Copyright IBM Corporation 2012

In short, if you are a PHP user, you are not alone

PHP Hides Its Complexity


You can build powerful e-commerce engines in PHP that handle millions of customers.
You can also build a small site that automatically maintains links to a changing list of articles or press releases.

When you're using PHP for a simpler project, it doesn't get in your way with concerns that are only relevant in a massive system.

Copyright IBM Corporation 2012

PHP Hides Its Complexity


When you need advanced features such as caching, custom libraries, or dynamic image generation, they are available. If you don't need them, you don't have to worry about them. You can just focus on the basics of handling user input and displaying output.

Copyright IBM Corporation 2012

PHP Is Built for Web Programming


Unlike most other programming languages, PHP was created from the ground up for generating web pages. This means that common web programming tasks, such as accessing form submissions and talking to a database, are often easier in PHP.
PHP comes with the capability to format HTML, manipulate dates and times, and manage web cookies tasks that are often available only as add-on libraries in other programming languages.
Copyright IBM Corporation 2012

HTML EMBEDDING
<HTML>
<HEAD>Sample PHP Script</HEAD>

<BODY>
The following prints "Hello, World":

<?php
print "Hello, World";

?>
</BODY>

</HTML>
Copyright IBM Corporation 2012

COMMENTS

You can write comments three different ways:


C way

/* This is a C like comment


* which can span multiple

* lines until the closing tags


*/

C++ way

// This is a C++ like comment which ends at the end of the line
Copyright IBM Corporation 2012

COMMENTS

Shell way

# This is a shell like comment which ends at the end of the line

Copyright IBM Corporation 2012

VARIABLES

Variables in PHP are quite different from compiled languages such as C and Java. This is because their weakly typed nature, which in short means you dont need to declare variables before using them. you dont need to declare their type and, as a result, a variable can change the type of its value as much as you want.

Copyright IBM Corporation 2012

VARIABLES

Variables in PHP are preceded with a$ sign, and similar to most modern languages. they can start with a letter (A-Z a-z) or_(underscore) and can then contain as many alphanumeric characters and underscores as you like.
Examples of legal variable names include

$count
$_Obj
Copyright IBM Corporation 2012

$A123

VARIABLES

Example of illegal variable names include

$123 $*ABC

As previously mentioned, you dont need to declare variables or their type before using them in PHP. The following code example uses variables: $PI = 3.14; $radius = 5;

Copyright IBM Corporation 2012

$circumference = $PI * 2 * $radius;

Indirect References to Variables

An extremely useful feature of PHP is that you can access variables by using indirect references, or to put it simply, you can create and access variables by name at run time.
Consider the following example:

$name = "John";
$$name = "Registered user";

print $John;
Copyright IBM Corporation 2012

This code results in the printing of"Registered user."

Managing Variables

Three language constructs are used to manage variables.

They enable you to check if certain variables exist, remove variables, and check variables truth values.

Copyright IBM Corporation 2012

Managing Variables

isset() determines whether a certain variable has already been declared by PHP. It returns a boolean value true. if the variable has already been set, and false

otherwise, or if the variable is set to the value NULL.


Consider the following script:

if (isset($first_name)) { print '$first_name is set';}


Copyright IBM Corporation 2012

Managing Variables

unset()

undeclares a previously set variable, and frees any memory that was used by it if no other variable references its value. A call to isset() on a variable that has been unset() returns false.

Copyright IBM Corporation 2012

Managing Variables

For example:

$name = "John Doe";


unset($name);

if (isset($name)) {
print $name is set'; }

This example will not generate any output, because isset() returns false.

Copyright IBM Corporation 2012

Managing Variables

empty() may be used to check if a variable has not been declared or its value is false. This language construct is usually used to check if a form variable has not been sent or does not contain data. When checking a variables truth value, its value is first converted to a Boolean according to the rules in the following section, and then it is checked for true/false.

Copyright IBM Corporation 2012

Managing Variables

For example:

if (empty($name)) {
print 'Error: Forgot to specify a value for $name'; } This code prints an error message if $name doesnt contain a value that evaluates to true.

Copyright IBM Corporation 2012

DATA TYPES

Eight different data types exist in PHP, five of which are scalar and each of the remaining three has its own uniqueness. The previously discussed variables can contain values of any of these data types without explicitly declaring their type. The variable behaves according to the data type it contains.

Copyright IBM Corporation 2012

Integers

Integers are whole numbers and are equivalent in range as your C compilers long value. On many common machines, such as Intel Pentiums, that means a 32-bit signed integer with a range between 2,147,483,648 to +2,147,483,647.
Integers can be written in decimal, hexadecimal (prefixed with 0x), and octal notation (prefixed with 0), and can include +/signs.

Copyright IBM Corporation 2012

Integers

Some examples of integers include

240000
0xABCD

007
-100

Copyright IBM Corporation 2012

Floating-Point Numbers

Floating-point numbers (also known as real numbers) represent real numbers and are equivalent to your platform C compilers double data type.

On common platforms, the data type size is 8 bytes and it has a range of approximately 2.2E308 to 1.8E+308.
Floating-point numbers include a decimal point and can include a +/- sign and an exponent value.

Copyright IBM Corporation 2012

Floating-Point Numbers

Examples of floating-point numbers include

3.14
+0.9e-2

-170000.5
54.6E42

Copyright IBM Corporation 2012

Strings

Strings in PHP are a sequence of characters that are always internally null terminated. However, unlike some other languages, such as C, PHP does not rely on the terminating null to calculate a strings length, but remembers its length internally.
When writing string values in your source code, you can use double quotes ("), single quotes (') or here-docs to delimit them.

Copyright IBM Corporation 2012

Double Quotes

Examples for double quotes:

"PHP: Hypertext Pre-processor"


"GET / HTTP/1.0\n"

"1234567890"

Strings can contain pretty much all characters. Some characters cant be written as is, however, and require special notation:

Copyright IBM Corporation 2012

Double Quotes

Strings can contain pretty much all characters. Some characters cant be written as is, however, and require special notation:

Copyright IBM Corporation 2012

Single Quotes

In addition to double quotes, single quotes may also delimit strings. The following table includes the only two escapings supported by single quotes: Examples:

'Hello, World'
'Today\'s the day'

Copyright IBM Corporation 2012

Here-Docs
Here-docs enable you to embed large pieces of text in your scripts, which may include lots of double quotes and single quotes, without having to constantly escape them. The following is an example of a here-doc: <<<THE_END PHP stands for "PHP: Hypertext Preprocessor".The acronym "PHP" is therefore, usually referred to as a recursive acronym THE_END

Copyright IBM Corporation 2012

Booleans
PHP automatically converts types when needed.
Boolean is probably the type that other types are most often converted to behind the scenes. This is because, in any conditional code such as if statements,loops, and so on, types are converted to this scalar type to check if the condition is satisfied.

Copyright IBM Corporation 2012

Booleans
Consider the following code fragment:
$numerator = 1;

$denominator = 5;
if ($denominator == 0) { print "The denominator needs to be a non-zero number\n"; }

Copyright IBM Corporation 2012

NULL
Null is a data type with only one possible value: the NULL value.
It marks variables as being empty, and its especially useful to differentiate between the empty string and null values of databases.

The isset($variable) operator of PHP returns false for NULL, and true for any other data type, as long as the variable youre testing exists.
The following is an example of using NULL:
Copyright IBM Corporation 2012

$value = NULL;

Constants
In PHP, you can define names, called constants, for simple values.
As the name implies, you cannot change these constants once they represent a certain value. The names for constants have the same rules as PHP variables except that they dont have the leading dollar sign.

Copyright IBM Corporation 2012

Constants
Unlike variables, constants, once defined, are globally accessible.
You dont have to (and cant) redeclare them in each new function and PHP file. To define a constant, use the following function: define("CONSTANT_NAME", value [, case_sensitivity])

Copyright IBM Corporation 2012

OPERATORS
PHP contains three types of operators: unary operators, binary operators, and one ternary operator. Binary operators are used on two operands:
2+3

14 * 3.1415
$i 1

These examples are also simple examples of expressions.


Copyright IBM Corporation 2012

OPERATORS
PHP can only perform binary operations on two operands that have the same type.
However, if the two operands have different types, PHP automatically converts one of them to the others type, according to the following rules.

Copyright IBM Corporation 2012

Numeric Operators
All the binary operators (except for the concatenation operator) work only on numeric operands. If one or both of the operands are strings, Booleans, nulls, or resources, they are automatically converted to their numeric equivalents before the calculation is performed (according to the previous table).

Copyright IBM Corporation 2012

Numeric Operators

Copyright IBM Corporation 2012

Concatenation Operator
The concatenation operator concatenates two strings. This operator works only on strings; thus, any non-string operand is first converted to one. The following example would print out "The year is 2000":

$year = 2000;
print "The year is " . $year;

Copyright IBM Corporation 2012

The integer $year is internally converted to the string "2000" before it is concatenated with the strings prefix, "The year is".

Assignment Operators
Assignment operators enable you to write a value to a variable.
The first operand (the one on the left of the assignment operator or l value) must be a variable. The value of an assignment is the final value assigned to the variable; for example, the expression $var = 5 has the value 5 (and assigns 5 to $var).

Copyright IBM Corporation 2012

Assignment Operators
In addition to the regular assignment operator =, several other assignment operators are composites of an operator followed by an equal sign.
These composite operators apply the operator taking the variable on the left as the first operand and the value on the right (the r value) as the second operand, and assign the result of the operation to the variable on the left.

Copyright IBM Corporation 2012

Assignment Operators
For example:
$counter += 2; // This is identical to $counter = $counter + 2; $offset *= $counter;// This is identical to $offset = $offset *

$counter;
The following list show the valid composite assignment operators: +=, -=, *=, /=, %=, ^=, .=, &=, |=, <<=, >>=
Copyright IBM Corporation 2012

By-Reference Assignment Operator


PHP enables you to create variables as aliases for other variables.
You can achieve this by using the by-reference assignment operator =&. After a variable aliases another variable, changes to either one of them affects the other.

Copyright IBM Corporation 2012

By-Reference Assignment Operator


For example:
$name = "Judy";

$name_alias =& $name;


$name_alias = "Jonathan"; print $name; The result of this example is Jonathan

Copyright IBM Corporation 2012

Comparison Operators
Comparison operators enable you to determine the relationship between two operands.
When both operands are strings, the comparison is performed lexicographically. The comparison results in a Boolean value.

For the following comparison operators, automatic type conversions are performed, if necessary.

Copyright IBM Corporation 2012

Comparison Operators

Copyright IBM Corporation 2012

Comparison Operators
For the following two operators, automatic type conversions are not performed and, therefore, both the types and the values are compared.

Copyright IBM Corporation 2012

Logical Operators
Logical operators first convert their operands to boolean values and then perform the respective comparison.

Copyright IBM Corporation 2012

Bitwise Operators
Bitwise operators perform an operation on the bitwise representation of their arguments.
Unless the arguments are strings, they are converted to their corresponding integer representation, and the operation is then performed. In case both arguments are strings, the operation is performed between corresponding character offsets of the two strings (each character is treated as an integer).
Copyright IBM Corporation 2012

Bitwise Operators

Copyright IBM Corporation 2012

Negation Operators
Negation operators appear before their operand for example, !$var (! is the operator, $var is the operand).

Copyright IBM Corporation 2012

Increment/Decrement Operators
Increment/decrement operators are unique in the sense that they operate only on variables and not on any value. The reason for this is that in addition to calculating the result value, the value of the variable itself changes as well.

Copyright IBM Corporation 2012

Increment/Decrement Operators
As you can see from the previous table, theres a difference in the value of post- and preincrement. However, in both cases, $var is incremented by 1.
The only difference is in the value to which the increment expression evaluates. Example 1: $num1 = 5; $num2 = $num1++;// post-increment, $num2 is assigned $num1's original value
Copyright IBM Corporation 2012

Increment/Decrement Operators
print $num1; // this will print the value of $num1, which is now 6
print $num2; // this will print the value of $num2, which is the original value of $num1, thus, 5

Example 2:
$num1 = 5;

$num2 = ++$num1;// pre-increment, $num2 is assigned $num1's incremented value


Copyright IBM Corporation 2012

Increment/Decrement Operators
print $num1; // this will print the value of $num1, which is now 6
print $num2; // this will print the value of $num2, which is the same as the value of $num1, thus, 6

The same rules apply to pre- and postdecrement.

Copyright IBM Corporation 2012

String Manipulation
The strtoupper() function converts a string to uppercase.
Example <?php echo strtoupper("Hello WORLD!"); ?> The output of the code above will be:

HELLO WORLD!

Copyright IBM Corporation 2012

String Manipulation
The strtolower() function converts a string to lowercase.
Example <?php echo strtolower("Hello WORLD."); ?> The output of the code above will be:

hello world.

Copyright IBM Corporation 2012

String Manipulation
The ucfirst() function converts the first character of a string to uppercase.
Example <?php echo ucfirst("hello world"); ?> The output of the code above will be:

Hello world

Copyright IBM Corporation 2012

String Manipulation
The ucwords() function converts the first character of each word in a string to uppercase.
Example <?php echo ucwords("hello world"); ?> The output of the code above will be:

Hello World

Copyright IBM Corporation 2012

String Manipulation
The strncmp() function compares two strings.
This function returns:

0 - if the two strings are equal


<0 - if string1 is less than string2 >0 - if string1 is greater than string2

Copyright IBM Corporation 2012

String Manipulation
Example
<?php echo strcmp("Hello world!","Hello world!"); ?> The output of the code above will be:

Copyright IBM Corporation 2012

String Manipulation
The strlen() function returns the length of a string.
Example <?php echo strlen("Hello world!"); ?> The output of the code above will be:

12

Copyright IBM Corporation 2012

String Manipulation
The substr() function returns a part of a string.
Example 1

<?php echo substr("Hello world!",6); ?> The output of the code above will be:
world!

Copyright IBM Corporation 2012

String Manipulation
Example 2
<?php echo substr("Hello world!",6,5); ?> The output of the code above will be:

world

Copyright IBM Corporation 2012

String Manipulation
The trim() function removes whitespaces and other predefined characters from both sides of a string. Example 1
<html> <body> <?php $str = " Hello World! "; echo "Without trim: " . $str; echo "<br />"; echo "With trim: " . trim($str); ?> <body> <html> The browser output of the code above will be: Without trim: Hello World! With trim: Hello World!

Copyright IBM Corporation 2012

String Manipulation
Example 2
<?php $str = "\r\nHello World!\r\n"; echo "Without trim: " . $str; echo "<br />"; echo "With trim: " . trim($str); ?> The browser output of the code above will be: Without trim: Hello World! With trim: Hello World!

Copyright IBM Corporation 2012

CONTROL STRUCTURES
PHP supports a variety of the most common control structures available in other programming languages. They can be basically divided into two groups:
-conditional control structures

-loop control structures.

Copyright IBM Corporation 2012

CONTROL STRUCTURES
The conditional control structures affect the flow of the program and execute or skip certain code according to certain criteria whereas loop control structures execute certain code an arbitrary number of times according to specified criteria.

Copyright IBM Corporation 2012

Conditional Control Structures


Conditional control structures are crucial in allowing your program to take different execution paths based on decisions it makes at runtime.
PHP supports both the if and switch conditional control structures.

Copyright IBM Corporation 2012

if Statements
if statements are the most common conditional constructs, and they exist in most programming languages. The expression in the if statement is referred to as the truth expression. If the truth expression evaluates to true, the statement or statement list following it are executed otherwise, theyre not.

Copyright IBM Corporation 2012

if Statements
Syntax
if (expr)

statement
elseif (expr) statement elseif (expr) statement else statement
Copyright IBM Corporation 2012

if Statements
You can add an else branch to an if statement to execute code only if all the truth expressions in the if statement evaluated to false: if ($var >= 50) {
print '$var is in range';

}
else {

print '$var is invalid';


}
Copyright IBM Corporation 2012

if Statements
The elseif construct can be used to conduct a series of conditional checks and only execute the code following the first condition that is met.
For example:
if ($num < 0) { print '$num is negative'; } elseif ($num == 0) {

print '$num is zero';


} elseif ($num > 0) {
Copyright IBM Corporation 2012

print '$num is positive';}

Switch Statements
You can use the switch construct to elegantly replace certain lengthy if/elseif constructs.
It is given an expression and compares it to all possible case expressions listed in its body. When theres a successful match, the following code is executed, ignoring any further case lines (execution does not stop when the next case is reached).

Copyright IBM Corporation 2012

The match is done internally using the regularequality operator (==), not the identical operator (===).

Switch Statements
You can use the break statement to end execution and skip to the code following the switch construct. Syntax
switch (expr){

case expr:
statement list case expr: statement list default:
Copyright IBM Corporation 2012

statement list }

Switch Statements
Example
switch ($answer) { case 'y': case 'Y': print "The answer was yes\n"; break; case 'n': case 'N': print "The answer was no\n"; break; default: print "Error: $answer is not a valid answer\n"; break;}
Copyright IBM Corporation 2012

While loops
while loops are the simplest kind of loops. In the beginning of each iteration, the whiles truth expression is evaluated. If it evaluates to true, the loop keeps on running and the statements inside it are executed.

Copyright IBM Corporation 2012

While loops
For example, heres one possible implementation of factorial, using a while loop(assuming $n contains the number for which we want to calculate the factorial):
$result = 1;

while ($n > 0) {


$result *= $n--;

}
print "The result is $result";
Copyright IBM Corporation 2012

do...while Loops
The do...while loop is similar to the previous while loop, except that the truth expression is checked at the end of each iteration instead of at the beginning. This means that the loop always runs at least once.
do { statement list if ($error) { break;} statement list } while (false);
Copyright IBM Corporation 2012

do...while Loops
Because do...while loops always iterate at least one time, the statements inside the loop are executed once, and only once. The truth expression is always false. However, inside the loop body, you can use the break statement to stop the execution of the statements at any point, which is convenient.
Of course, do...while loops are also often used for regular iterating purposes.
Copyright IBM Corporation 2012

for Loops
The start expression is evaluated only once when the loop is reached.
Usually it is used to initialize the loop control variable. The truth expression is evaluated in the beginning of every loop iteration. If true, the statements inside the loop will be executed; if false, the loop ends.

Copyright IBM Corporation 2012

for Loops
The increment expression is evaluated at the end of every iteration before the truth expression is evaluated. Usually, it is used to increment the loop control variable, but it can be used for any other purpose as well. Both break and continue behave the same way as they do with while loops. continue causes evaluation of the increment expression before it re-evaluates the truth expression.
Copyright IBM Corporation 2012

for Loops
Heres an example:
for ($i = 0; $i < 10; $i++) {

print "The square of $i is " . $i*$i . "\n";


} The result of running this code is The square of 0 is 0 The square of 1 is 1 ... The square of 9 is 81
Copyright IBM Corporation 2012

FUNCTIONS
A function in PHP can be built-in or userdefined.
However, they are both called the same way. The general form of a function call is func(arg1,arg2,) The number of arguments varies from one function to another.

Each argument can be any valid expression, including other function calls.
Copyright IBM Corporation 2012

FUNCTIONS
Here is a simple example of a predefined function:
$length = strlen("John"); strlen is a standard PHP function that returns the length of a string.

Therefore, $length is assigned the length of the string "John": four. Heres an example of a function call being used as a function argument:
$length = strlen(strlen("John"));
Copyright IBM Corporation 2012

FUNCTIONS
You probably already guessed the result of this example.
First, the inner strlen("John") is executed, which results in the integer 4. So, the code simplifies to

$length = strlen(4);
strlen() expects a string, and therefore (due to PHPs magical autoconversion between types) converts the integer 4 to the string "4", and thus, the resulting value of $length is 1, the length of "4".
Copyright IBM Corporation 2012

User-Defined Functions
The general way of defining a function is
function function_name (arg1, arg2, arg3, )

{
statement list } To return a value from a function, you need to make a call to return expr inside your function.

This stops execution of the function and returns expr as the functions value.
Copyright IBM Corporation 2012

The following example function accepts one argument, $x, and returns its square:
function square ($x){ return $x*$x;} After defining this function, it can be used as an expression wherever you desire. For example:

User-Defined Functions

print 'The square of 5 is ' . square(5);


Copyright IBM Corporation 2012

Function Scope
Every function has its own set of variables. Any variables used outside the functions definition are not accessible from within the function by default.
When a function starts, its function parameters are defined. When you use new variables inside a function, they are defined within the function only and dont hang around after the function call ends.
Copyright IBM Corporation 2012

Function Scope
In the following example, the variable $var is not changed by the function call:
function func () { $var = 2; } $var = 1;

func();
print $var;
Copyright IBM Corporation 2012

Function Scope
When the function func is called, the variable $var, which is assigned 2, is only in the scope of the function and thus does not change $var outside the function.
The code snippet prints out 1.

Now what if you actually do want to access and/or change $var on the outside?
you can use the built-in $GLOBALS[] array to access variables in the global scope of the script.
Copyright IBM Corporation 2012

Function Scope
Rewrite the previous script the following way:
function func ()

{
$GLOBALS["var"] = 2; } $var = 1; func(); print $var; It prints the value 2.
Copyright IBM Corporation 2012

Returning Values By Value


The return statement returns values by value, which means that a copy of the value is created and is returned to the caller of the function. For example:
function get_global_variable_value($name){

return $GLOBALS[$name]; }
$num = 10;

$value = get_global_variable_value("num");
print $value;
Copyright IBM Corporation 2012

Returning Values By Value


This code prints the number 10. However, making changes to $value before the print statement only affects $value and not the global variable $num.
This is because its value was returned by the get_global_variable_value() by value and not by reference.

Copyright IBM Corporation 2012

Declaring Function Parameters


you can pass an arbitrary amount of arguments to a function.
There are two different ways of passing these arguments. The first is the most common, which is called passing by value, and the second is called passing by reference. Which kind of argument passing you would like is specified in the function definition itself and not during the function call.
Copyright IBM Corporation 2012

By-Value Parameters
The argument can be any valid expression, the expression is evaluated, and its value is assigned to the corresponding variable in the function.

For example, here, $x is assigned the value 8 and $y is assigned the value of $c:
function pow($x, $y) { ... }
Copyright IBM Corporation 2012

pow(2*4, $c);

By-Reference Parameters
Passing by-reference requires the argument to be a variable.
Instead of the variables value being passed, the corresponding variable in the function directly refers to the passed variable whenever used. Thus, if you change it inside the function, it affects the sent variable in the outer scope as well
Copyright IBM Corporation 2012

By-Reference Parameters

Example

function square(&$n)
{ $n = $n*$n; } $number = 4; square($number); print $number;
Copyright IBM Corporation 2012

By-Reference Parameters
The & sign that proceeds $n in the function parameters tells PHP to pass it by-reference, and the result of the function call is $number squared.
thus, this code would print 16.

Copyright IBM Corporation 2012

Default Parameters
Default parameters enable you to specify a default value for function parameters that arent passed to the function during the function call.
The default values you specify must be a constant value, such as a scalar, array with scalar values, or constant.

Copyright IBM Corporation 2012

Default Parameters
The following is an example for using default parameters:
function increment(&$num, $increment = 1) { $num += $increment; } $num = 4;

increment($num);
increment($num, 3);
Copyright IBM Corporation 2012

Default Parameters
This code results in $num being incremented to 8.
First, it is incremented by 1 by the first call to increment, where the default increment size of 1 is used, and second, it is incremented by 3, altogether by 4.

Copyright IBM Corporation 2012

Static Variables
Like C, PHP supports declaring local function variables as static.
These kind of variables remain in tact in between function calls, but are still only accessible from within the function they are declared. Static variables can be initialized,and this initialization only takes place the first time the static declaration is reached.
Copyright IBM Corporation 2012

Static Variables

Heres an example for the use of static that runs initialization code the
first time (and only the first time) the function is run:

function do_something() { static first_time = true; if (first_time) { // Execute this code only the first time the function is called ... } // Execute the function's main logic every time the function iscalled
Copyright IBM Corporation 2012

The Include Function


The include function takes a file name and simply inserts that file's contents into the script that calls used the include function. This means that you can type up a common header or menu file that you want all your web pages to include.
When you add a new page to your site, instead of having to update the links on several web pages, you can simply change the Menu file.
Copyright IBM Corporation 2012

An Include Example
A common practice for naming files that are to be included is to use the ".php" extension. Since we want to create a common menu let's save it as "menu.php".
menu.php Code:
<html> <body> <ahref="http://www.example.com/index.php">Home</a> <ahref="http://www.example.com/about.php">About Us</a> <ahref="http://www.example.com/links.php">Links</a> <ahref="http://www.example.com/contact.php">Contact Us</a> <br />

Copyright IBM Corporation 2012

An Include Example
Here we will take advantage of the include function to add our common menu.

index.php Code: <?php include("menu.php"); ?> <p>This is my home page that uses a common menu to save me time when I add new pages to my website!</p>

</body>
</html>
Copyright IBM Corporation 2012

PHP Require Function


When you include a file with the include function and PHP cannot find it you will see an error message like the following:
PHP Code:
<?php include("noFileExistsHere.php");

echo "Hello World!";


?> Display: Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2 Warning: main(): Failed opening 'noFileExistsHere.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/websiteName/FolderName/tizagScript.php on line 2 Hello World!
Copyright IBM Corporation 2012

PHP Require Function


PHP Code:
<?php require("noFileExistsHere.php");

echo "Hello World!";


?> Display:

Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2 Fatal error: main(): Failed opening required 'noFileExistsHere.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/websiteName/FolderName/tizagScript.php on line 2

Copyright IBM Corporation 2012

PHP Require Function


The echo statement was not executed because our script execution died after the require function returned a fatal error. We recommend that you use require instead of include because your scripts should not be executing if necessary files are missing or misnamed.

Copyright IBM Corporation 2012

Arrays
Arrays are collections of related values, such as the data submitted from a form, the names of students in a class, or the populations of a list of cities.
An array is a container that holds multiple values, each distinct from the rest. An array is made up of elements. Each element has a key and a value.

Copyright IBM Corporation 2012

Arrays
An array holding information about the colors of vegetables has vegetable names for keys and colors for values, shown below

Copyright IBM Corporation 2012

Arrays
An array can only have one element with a given key.
In the vegetable color array, there can't be another element with the key corn even if its value is blue.

However, the same value can appear many times in one array.
You can have orange carrots, orange tangerines, and orange oranges.
Copyright IBM Corporation 2012

Arrays
Any string or number value can be an array element key such as corn, 4, -36, or Salt Baked Squid. Arrays and other non-scalar[1] values can't be keys, but they can be element values An element value can be a string, a number, true, or false; it can also be another array.

Copyright IBM Corporation 2012

Creating an Array
To create an array, assign a value to a particular array key. Array keys are denoted with square brackets, // An array called $vegetables with string keys
$vegetables['corn'] = 'yellow';

$vegetables['beet'] = 'red';
$vegetables['carrot'] = 'orange';

Copyright IBM Corporation 2012

Creating an Array
You can also create an array using the array( ) language construct.
Creating arrays with array( ) $vegetables = array('corn' => 'yellow', 'beet' => 'red', 'carrot' => 'orange'); With array( ), you specify a comma-delimited list of key/value pairs.

The key and the value are separated by =>.


Copyright IBM Corporation 2012

Creating an Array
The array( ) syntax is more concise when you are adding more than one element to an array at a time. The square bracket syntax is better when you are adding elements one by one.

Copyright IBM Corporation 2012

Creating a Numeric Array


PHP provides some shortcuts for working with arrays that have only numbers as keys.
If you create an array with array() by specifying only a list of values instead of key/value pairs, the PHP interpreter automatically assigns a numeric key to each value. The keys start at 0 and increase by 1 for each element. below example uses this technique to create the $dinner array.
Copyright IBM Corporation 2012

Creating a Numeric Array


Example :Creating numeric arrays with array( )
$dinner = array('Sweet Corn and Asparagus',

'Lemon Chicken','Braised Bamboo Fungus');


print "I want $dinner[0] and $dinner[1]."; Example prints: I want Sweet Corn and Asparagus and Lemon Chicken.

Copyright IBM Corporation 2012

Creating a Numeric Array


Internally, the PHP interpreter treats arrays with numeric keys and arrays with string keys (and arrays with a mix of numeric and string keys) identically.
Because of the resemblance to features in other programming languages,programmers often refer to arrays with only numeric keys as "numeric," "indexed," or "ordered" arrays, and to string-keyed arrays as "associative" arrays.

Copyright IBM Corporation 2012

Finding the Size of an Array


The count( ) function tells you the number of elements in an array.
Example. Finding the size of an array $dinner = array('Sweet Corn and Asparagus', 'Lemon Chicken','Braised Bamboo Fungus'); $dishes = count($dinner); print "There are $dishes things for dinner.";

Example prints:
There are 3 things for dinner.
Copyright IBM Corporation 2012

Looping Through Arrays


One of the most common things to do with an array is to consider each element in the array individually and process it somehow. This may involve incorporating it into a row of an HTML table or adding its value to a running total.
The easiest way to iterate through each element of an array is with foreach( ).

The foreach( ) construct lets you run a code block once for each element in an array.
Copyright IBM Corporation 2012

Looping Through Arrays


Example uses foreach( ) to print an HTML table containing each element in an array.
$meal = array('breakfast' => 'Walnut Bun',

'lunch' => 'Cashew Nuts and White Mushrooms','snack' => 'Dried Mulberries', 'dinner' => 'Eggplant with Chili Sauce');
print "<table>\n"; foreach ($meal as $key => $value) { print "<tr><td>$key</td><td>$value</td></tr>\n";

}
print '</table>';
Copyright IBM Corporation 2012

Looping Through Arrays

Example prints:
<table>

<tr><td>breakfast</td><td>Walnut Bun</td></tr>
<tr><td>lunch</td><td>Cashew Nuts and White Mushrooms</td></tr> <tr><td>snack</td><td>DriedMulberries</td></ tr> <tr><td>dinner</td><td>Eggplant with Chili Sauce</td></tr> </table>
Copyright IBM Corporation 2012

Looping Through Arrays


For each element in $meal, foreach( ) copies the key of the element into $key and the value into $value. Then, it runs the code inside the curly braces. In Example , that code prints $key and $value with some HTML to make a table row.
You can use whatever variable names you want for the key and value inside the code block. If the variable names were in use before the foreach( ), though, they're overwritten with values from the array.
Copyright IBM Corporation 2012

Modifying Arrays
You can operate on individual array elements just like regular scalar variables, using arithmetic, logical, and other operators.
Example . Operating on array elements
$dishes['Beef Chow Foon'] = 12; $dishes['Beef Chow Foon']++;

$dishes['Roast Duck'] = 3;
$dishes['total'] = $dishes['Beef Chow Foon'] + $dishes['Roast Duck']; if ($dishes['total']> 15) { print "You ate a lot: ";} print 'You ate ' . $dishes['Beef Chow Foon'] . ' dishes of Beef Chow Foon.'; Example prints:
Copyright IBM Corporation 2012

You ate a lot: You ate 13 dishes of Beef Chow Foon.

Converting an Array to String


When you want to print all of the values in an array at once, the quickest way is to use the implode( ) function. It makes a string by combining all the values in an array and separating them with a string delimiter. Example prints a comma separated list of dim sum choices.

Copyright IBM Corporation 2012

Converting an Array to String


$dimsum = array('Chicken Bun','Stuffed Duck Web','Turnip Cake'); $menu = implode(', ', $dimsum); print $menu;

Example prints:
Chicken Bun, Stuffed Duck Web, Turnip Cake To implode an array with no delimiter, use the empty string as the first argument to implode( ): $letters = array('A','B','C','D'); print implode(' ',$letters);

This prints:
ABCD
Copyright IBM Corporation 2012

Converting an String to Array


The counterpart to implode( ) is called explode( ). It breaks a string apart into an array.
The delimiter argument to explode( ) is the string it should look for to separate array elements. Example demonstrates explode( ).

$fish = 'Bass, Carp, Pike, Flounder';


$fish_list = explode(', ', $fish);

print "The second fish is $fish_list[1]";


Example prints:
Copyright IBM Corporation 2012

The second fish is Carp

Sorting Arrays
There are several ways to sort arrays. Which function to use depends on how you want to sort your array and what kind of array it is. The sort( ) function sorts an array by its element values. It should only be used on numeric arrays, because it resets the keys of the array when it sorts.

Copyright IBM Corporation 2012

Sorting Arrays
Example
$dinner = array('Sweet Corn and Asparagus', 'Lemon Chicken','Braised Bamboo Fungus'); print "Before Sorting:\n"; foreach ($dinner as $key => $value) {

print " \$dinner: $key $value\n";}


sort($dinner);

print "After Sorting:\n";


foreach ($dinner as $key => $value) {
Copyright IBM Corporation 2012

print " \$dinner: $key $value\n";}

Sorting Arrays
Before Sorting:
$dinner: 0 Sweet Corn and Asparagus

$dinner: 1 Lemon Chicken


$dinner: 2 Braised Bamboo Fungus After Sorting:

$dinner: 0 Braised Bamboo Fungus $dinner: 1 Lemon Chicken $dinner: 2 Sweet Corn and Asparagus
Copyright IBM Corporation 2012

Sorting Arrays
While sort( ) and asort( ) sort arrays by element value, you can also sort arrays by key with ksort( ). This keeps key/value pairs together, but orders them by key. Example shows $meal sorted with ksort( ).

Copyright IBM Corporation 2012

Sorting Arrays
$meal = array('breakfast' => 'Walnut Bun','lunch' => 'Cashew Nuts andWhiteMushrooms', 'snack' => 'Dried Mulberries', 'dinner' => 'Eggplant with Chili Sauce'); print "Before Sorting:\n"; foreach ($meal as $key => $value) { print " \$meal: $key $value\n";}

ksort($meal);
print "After Sorting:\n"; foreach ($meal as $key => $value) { print " \$meal: $key $value\n"; }
Copyright IBM Corporation 2012

Sorting Arrays
Example prints:
Before Sorting: $meal: breakfast Walnut Bun

$meal: lunch Cashew Nuts and White Mushrooms


$meal: snack Dried Mulberries $meal: dinner Eggplant with Chili Sauce After Sorting: $meal: breakfast Walnut Bun

$meal: dinner Eggplant with Chili Sauce


$meal: lunch Cashew Nuts and White Mushrooms $meal: snack Dried Mulberries
Copyright IBM Corporation 2012

Sorting Arrays
The array is reordered so the keys are now in ascending alphabetical order.
Each element is unchanged, so the value that went with each key before the sorting is the same as each key value after the sorting.

If you sort a numeric array with ksort( ), then the elements are ordered so the keys are in ascending numeric order. This is the same order you start out with when you create a numeric array using array( ) or [ ].
Copyright IBM Corporation 2012

Using Multidimensional Arrays


The value of an array element can be another array.
This is useful when you want to store data that has a more complicated structure than just a key and a single value.

A standard key/value pair is fine for matching up a meal name with a single dish but what about when each meal consists of more than one dish? Then, element values should be arrays, not strings.
Copyright IBM Corporation 2012

Using Multidimensional Arrays


$meals = array('breakfast' => array('Walnut Bun','Coffee'),'lunch' => array('Cashew Nuts', 'White Mushrooms'),'snack' => array('Dried Mulberries','Salted Sesame Crab'));

$lunches=>array( array('Chicken','Eggplant','Rice'),array('Beef', 'Scallions','Noodles'),array('Eggplant','Tofu')) ;

$flavors = array('Japanese' => array('hot' => 'wasabi','salty' => 'soy sauce'),'Chinese' => array('hot' => 'mustard','pepper-salty' =>
Copyright IBM Corporation 2012

Accessing multidimensional array


Accessing multidimensional array elements
print $meals['lunch'][1]; // White Mushrooms

print $meals['snack'][0]; // Dried Mulberries


print $lunches[0][0]; // Chicken print $lunches[2][1]; // Tofu print $flavors['Japanese']['salty'] // soy sauce print $flavors['Chinese']['hot']; // mustard

Copyright IBM Corporation 2012

Iterating multidimensional array


$flavors = array('Japanese' => array('hot' => 'wasabi','salty' => 'soy sauce'),'Chinese' => array('hot' => 'mustard','peppersalty' => 'prickly ash')); // $culture is the key and $culture_flavors is the value (an array) foreach ($flavors as $culture => $culture_flavors) { // $flavor is the key and $example is the value foreach ($culture_flavors as $flavor => $example) { print "A $culture $flavor flavor is $example.\n";

}
}
Copyright IBM Corporation 2012

Iterating multidimensional array


Example prints:
A Japanese hot flavor is wasabi.

A Japanese salty flavor is soy sauce.


A Chinese hot flavor is mustard. A Chinese pepper-salty flavor is prickly ash.

Copyright IBM Corporation 2012

PHP FILE HANDLING


Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and editing files.
When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong. Common errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.
Copyright IBM Corporation 2012

PHP - File Create


In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call. So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending.

Copyright IBM Corporation 2012

PHP - File Create


The fopen function needs two important pieces of information to operate correctly.
First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc). Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file.
Copyright IBM Corporation 2012

PHP - File Create


PHP Code:
$ourFileName = "testFile.txt";

$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");


fclose($ourFileHandle); The file "testFile.txt" should be created in the same directory where this PHP code resides.

PHP will see that "testFile.txt" does not exist and will create it after running this code.
Copyright IBM Corporation 2012

PHP - File Create


Here we create the name of our file, "testFile.txt" and store it into a PHP String variable $ourFileName. First we use the function fopen and give it two arguments: file name and we inform PHP that we want to write by passing the character "w".
Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file.
Copyright IBM Corporation 2012

We save the file handle into the $ourFileHandle variable.

FileModes
The following table shows the different modes the file may be opened in.

Copyright IBM Corporation 2012

PHP - Different Ways to Open a File


PHP requires you to specify your intentions when you open a file.
Read: 'r' Open a file for read only use. The file pointer begins at the front of the file. Write: 'w' Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the beginning of the file. This is also called truncating a file, which we will talk about more in a later lesson. The file pointer

Copyright IBM Corporation 2012

PHP - Different Ways to Open a File


Append: 'a'
Open a file for write only use. However, the data in the file is preserved and you begin will writing data at the end of the file. The file pointer begins at the end of the file.

Copyright IBM Corporation 2012

PHP - Different Ways to Open a File


Read/Write: 'r+' Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file. Write/Read: 'w+'

This is exactly the same as r+, except that it deletes all information in the file when the file is opened. Append: 'a+'
This is exactly the same as r+, except that the file pointer is at the end of the file
Copyright IBM Corporation 2012

Closing a File
The fclose function is used to close a file when you are finished with it.
fclose($fp);

Copyright IBM Corporation 2012

PHP - File Write


We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite's first parameter is the file handle and its second parameter is the string of data that is to be written.
Just give the function those two bits of information.

Copyright IBM Corporation 2012

PHP - File Write


Below we are writing a couple of names into our test file testFile.txt and separating them with a carriaged return. PHP Code:
$myFile = "testFile.txt"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "Bobby Bopper\n"; fwrite($fh, $stringData);

$stringData = "Tracy Tanner\n";


fwrite($fh, $stringData); fclose($fh);
Copyright IBM Corporation 2012

PHP - File Write


The $fh variable contains the file handle for testFile.txt.
The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.

We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the string $stringData that first contained Bobby Bopper and second contained Tracy Tanner.
Copyright IBM Corporation 2012

PHP - File Write


After we finished writing we closed the file using the fclose function.
If you were to open the testFile.txt file in NOTEPAD it would look like this: Contents of the testFile.txt File:

Bobby Bopper
Tracy Tanner

Copyright IBM Corporation 2012

PHP - File Write: Overwriting


Now that testFile.txt contains some data we can demonstrate what happens when you open an existing file for writing. All the data contained in the file is wiped clean and you start with an empty file. In this example we open our existing file testFile.txt and write some new data into it.

Copyright IBM Corporation 2012

PHP - File Write: Overwriting


PHP Code:
$myFile = "testFile.txt";

$fh = fopen($myFile, 'w') or die("can't open file");


$stringData = "Floppy Jalopy\n"; fwrite($fh, $stringData); $stringData = "Pointy Pinto\n";

fwrite($fh, $stringData);
fclose($fh);
Copyright IBM Corporation 2012

PHP - File Write: Overwriting


If you now open the testFile.txt file you will see that Bobby and Tracy have both vanished, as we expected, and only the data we just wrote is present.
Contents of the testFile.txt File:

Floppy Jalopy
Pointy Pinto

Copyright IBM Corporation 2012

PHP - File Read


The fread function is the staple for getting data out of a file.
The function requires a file handle, which we have, and an integer to tell the function how much data, in bytes, it is supposed to read.

One character is equal to one byte. If you wanted to read the first five characters then you would use five as the integer.

Copyright IBM Corporation 2012

PHP - File Read


PHP Code:
$myFile = "testFile.txt";

$fh = fopen($myFile, 'r');


$theData = fread($fh, 5); fclose($fh); echo $theData; Display: Flopp
Copyright IBM Corporation 2012

PHP - File Read


If you wanted to read all the data from the file, then you need to get the size of the file.
The filesize function returns the length of a file, in bytes, which is just what we need. The filesize function requires the name of the file that is to be sized up.

Copyright IBM Corporation 2012

PHP - File Read


PHP Code:
$myFile = "testFile.txt";

$fh = fopen($myFile, 'r');


$theData = fread($fh, filesize($myFile)); fclose($fh); echo $theData; Display: Floppy Jalopy Pointy Pinto
Copyright IBM Corporation 2012

PHP - File Read: gets Function


PHP also lets you read a line of data at a time from a file with the gets function.
If you had separated your data with new lines then you could read in one segment of data at a time with the gets function.

Copyright IBM Corporation 2012

PHP - File Read: gets Function


PHP Code:
$myFile = "testFile.txt";

$fh = fopen($myFile, 'r');


$theData = fgets($fh); fclose($fh); echo $theData; testFile.txt Contents: Floppy Jalopy
Copyright IBM Corporation 2012

PHP - File Append


Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data. PHP Code:
$myFile = "testFile.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "New Stuff 1\n"; fwrite($fh, $stringData);

$stringData = "New Stuff 2\n";


fwrite($fh, $stringData); fclose($fh);
Copyright IBM Corporation 2012

PHP - File Append


You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.
The contents of the file testFile.txt would now look like this:

Contents of the testFile.txt File:


Copyright IBM Corporation 2012

Floppy Jalopy Pointy Pinto New Stuff 1 New Stuff 2

Objects
The main difference in OOP as opposed to functional programming is that the data and code are bundled together into one entity, which is known as an object.
Object-oriented applications are usually split up into a number of objects that interact with each other. Each object is usually an entity of the problem, which is self-contained and has a bunch of properties and methods.
Copyright IBM Corporation 2012

Objects
The properties are the objects data ,which basically means the variables that belong to the object. The methods if you are coming from a functional background are basically the functions that the object supports.
Going one step further, the functionality that is intended for other objects to be accessed and used during interaction is called an objects interface.
Copyright IBM Corporation 2012

Classes
A class is a template for an object and describes what methods and properties an object of this type will have. In this example, the class represents a person. For each person in your application,you can make a separate instance of this class that represents the persons information.

Copyright IBM Corporation 2012

Classes
For example, if two people in our application are called Joe and Judy, we would create two separate instances of this class and would call the setName() method of each with their names to initialize the variable holding the persons name, $name.
The methods and members that other interacting objects may use are a classs contract. In this example, the persons contracts to the outside world are the two set and get methods,setName() and getName().
Copyright IBM Corporation 2012

Classes
Diagram of class Person

Copyright IBM Corporation 2012

Classes
The following PHP code defines the class, creates two instances of it, sets the name of each instance appropriately, and prints the names:
class Person { private $name;

function setName($name)
{ $this->name = $name;

Copyright IBM Corporation 2012

Classes
function getName() { return $this->name; } }; $judy = new Person(); $judy->setName("Judy");

$joe = new Person();


$joe->setName("Joe"); print $judy->getName() . "\n";

print $joe->getName(). "\n";

Copyright IBM Corporation 2012

Defining Class in PHP


You use the class keyword,give the class a name,and list all the methods and properties an instance of this class should have: class MyClass {
... // List of methods

...
... // List of properties

...
}
Copyright IBM Corporation 2012

CONSTRUCTORS
Instances of classes are created using the new
keyword.

In the previous example,we created a new instance of the Person class using $judy = new Person();. What happens during the new call is that a new object is allocated with its own copies of the properties defined in the class you requested, and then the constructor of the object is called in case one was defined.
Copyright IBM Corporation 2012

CONSTRUCTORS
The constructor is a metho named__construct() which is automatically called by the new keyword after creating the object. It is usually used to automatically perform various initializations such as property initializations.
Constructors can also accept arguments, in which case, when the new statement is written, you also need to send the constructor the function parameters in between the parentheses.
Copyright IBM Corporation 2012

CONSTRUCTORS
Example
class Person { function __construct($name){ $this->name = $name; } function getName(){ return $this->name;} private $name; }; $judy = new Person("Judy") . "\n"; $joe = new Person("Joe") . "\n"; print $judy->getName(); print $joe->getName();
Copyright IBM Corporation 2012

DESTRUCTORS
Destructor functions are the opposite of constructors.

They are called when the object is being destroyed (for example, when there are no more referencesto the object).
As PHP makes sure all resources are freed at the end of each request, the importance of destructors is limited. However, they can still be useful for performing certain actions, such as flushing a resource or logging information on object destruction.
Copyright IBM Corporation 2012

DESTRUCTORS
There are two situations where your destructor might be called: during your scripts execution when all references to an object are destroyed, or when the end of the script is reached and PHP ends the request.
The latter situation is delicate because you are relying on some objects that might already have had their destructors called and are not accessible anymore. So, use it with care, and dont rely on other objects in your destructors.
Copyright IBM Corporation 2012

public, protected and private Properties


A key paradigm in OOP is encapsulation and access protection of object properties (also referred to as member variables). Most common OO languages have three main access restriction keywords: public, protected, and private.
When defining a class member in the class definition, the developer needs to specify one of these three access modifiers before declaring the member itself.
Copyright IBM Corporation 2012

public, protected and private Properties


This example will be built upon to demonstrate the use of these access modifiers.
class MyClass {

public $publicMember = "Public member";


protected $protectedMember = "Protected member"; private $privateMember = "Private member"; function myMethod(){ // ...

}
}
Copyright IBM Corporation 2012

$obj = new MyClass();

Public
Public members can be accessed both from outside an object by using $obj->publicMember and by accessing it from inside the myMethod method via the special $this variable (for example, $this->publicMember).
If another class inherits a public member, the same rules apply, and it can be accessed both from outside the derived classs objects and from within its methods.
Copyright IBM Corporation 2012

Protected
Protected members can be accessed only from within an objects method for example, $this->protectedMember. If another class inherits a protected member, the same rules apply, and it can be accessed from within the derived objects methods via the special $this variable.

Copyright IBM Corporation 2012

Private
Private members are similar to protected members because they can be accessed only from within an objects method. However, they are also inaccessible from a derived objects methods. Because private properties arent visible from inheriting classes, two related classes may declare the same private properties. Each class will see its own private copy, which are unrelated.
Copyright IBM Corporation 2012

public,protected and private Methods


Access modifiers may also be used in conjunction with object methods, and the rules are the same: public methods can be called from any scope.
protected methods can only be called from within one of its class methods or from within an inheriting class. private methods can only be called from within one of its class methods and not from an inheriting class.
Copyright IBM Corporation 2012

public,protected and private Methods


As with properties, private methodsmay be redeclared by inheriting classes.
Each class will see its own version of the method.
class MyDbConnectionClass { public function connect() { $conn = $this->createDbConnection(); $this->setDbConnection($conn); return $conn;} protected function createDbConnection(){ return mysql_connect("localhost");}
Copyright IBM Corporation 2012

public,protected and private Methods


private function setDbConnection($conn){ $this->dbConnection = $conn; } private $dbConnection; } class MyFooDotComDbConnectionClass extends MyDbConnectionClass {

protected function createDbConnection(){


return mysql_connect("foo.com"); }

Copyright IBM Corporation 2012

public,protected and private Methods


This skeleton code example could be used for a database connection class.
The connect() method is meant to be called by outside code. The createDbConnection() method is an internal method but enables you to inherit from the class and change it. Thus, it is marked as protected. The setDbConnection() method is completely internal to the class and is therefore marked as private.

Copyright IBM Corporation 2012

Static Properties
As you know by now, classes can declare properties.
Each instance of the class (i.e., object) has its own copy of these properties. However, a class can also contain static properties. Unlike regular properties, these belong to the class itself and not to any instance of it. Therefore, they are often called class properties as opposed to object or instance properties.
Copyright IBM Corporation 2012

Static Properties
Static properties are defined by using the static keyword:
class MyClass { static $myStaticVariable; static $myInitializedStaticVariable = 0;} To access static properties, you have to qualify the property name with the class it sits in

MyClass::$myInitializedStaticVariable++;
print MyClass::$myInitializedStaticVariable;
Copyright IBM Corporation 2012

This example prints the number 1.

Static Properties
One example of using it is to assign a unique id to all instances of a class:
class MyUniqueIdClass {

static $idCounter = 0;
public $uniqueId; function __construct(){ self::$idCounter++; $this->uniqueId = self::$idCounter;}} $obj1 = new MyUniqueIdClass(); print $obj1->uniqueId . "\n";

$obj2 = new MyUniqueIdClass();


print $obj2->uniqueId . "\n"; This prints
Copyright IBM Corporation 2012

Static Methods
Similar to static properties, PHP supports declaring methods as static.
What this means is that your static methods are part of the class and are not bound to any specific object instance and its properties.

Therefore, $this isnt accessible in these methods, but the class itself is by using self to access it.

Copyright IBM Corporation 2012

Static Methods
Because static methods arent bound to any specific object, you can call them without creating an object instance by using the class_name::method() syntax.
You may also call them from an object instance using $this->method(), but $this wont be defined in the called method. For clarity, you should use self::method() instead of $this->method().

Copyright IBM Corporation 2012

Static Methods
Heres an example:
class PrettyPrinter { static function printHelloWorld(){

print "Hello, World";


self::printNewline();} static function printNewline(){ print "\n";} } PrettyPrinter::printHelloWorld(); The example prints the string "Hello, World"

Copyright IBM Corporation 2012

CLASS CONSTANTS
Global constants have existed in PHP for a long time.
Similar to static members,they belong to theclass and not to instances of the class. Class constants are always case-sensitive.

The declaration syntax is intuitive, and accessing constants is similar to accessing static members.

Copyright IBM Corporation 2012

CLASS CONSTANTS
class MyColorEnumClass { const RED = "Red"; const GREEN = "Green";

const BLUE = "Blue";


function printBlue(){ print self::BLUE;}

}
print MyColorEnumClass::RED; $obj = new MyColorEnumClass();

$obj->printBlue();
This code prints "Red" followed by "Blue".
Copyright IBM Corporation 2012

parent:: AND self::


PHP supports two reserved class names that make it easier when writing OO applications.
self:: refers to the current class and it is usually used to access static members, methods, and constants.

parent:: refers to the parent class and it is most often used when wanting to call the parent constructor or methods. It may also be used to access members and constants.
Copyright IBM Corporation 2012

parent:: AND self::


You should use parent:: as opposed to the parents class name because it makes it easier to change your class hierarchy because you are not hard-coding the parents class name.
The following example makes use of both parent:: and self:: for accessing the Child and Ancestor classes:
class Ancestor { const NAME = "Ancestor"; function __construct(){ print "In " . self::NAME . " constructor\n";} }
Copyright IBM Corporation 2012

parent:: AND self::


class Child extends Ancestor { const NAME = "Child"; function __construct(){

parent::__construct();
print "In " . self::NAME . " constructor\n";} } $obj = new Child(); The previous example outputs In Ancestor constructor In Child constructor
Copyright IBM Corporation 2012

EXCEPTION HANDLING
Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.
The current code state is saved.

The code execution will switch to a predefined (custom) exception handler function.
Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code.

Copyright IBM Corporation 2012

Basic Use of Exceptions


When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.

Copyright IBM Corporation 2012

Basic Use of Exceptions


Lets try to throw an exception without catching it:
<?php

//create function with an exception


function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below");} return true;} //trigger exception checkNum(2); ?> The code above will get an error like this:

Fatal error: Uncaught exception 'Exception'with message 'Value must be 1 or below' in C:\webfolder\test.php:6 Stack trace: #0 C:\webfolder\test.php(12):checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6
Copyright IBM Corporation 2012

Try, throw and catch


To avoid the error from the example above, we need to create the proper code to handle an exception. Proper exception code should include:
Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown"
Copyright IBM Corporation 2012

Try, throw and catch


Throw - This is how you trigger an exception.
Each "throw" must have at least one "catch"

Catch - A "catch" block retrieves an exception and creates an object containing the exception information

Copyright IBM Corporation 2012

Try, throw and catch


Lets try to trigger an exception with valid code:
<?php //create function with an exception function checkNum($number){ if($number>1) { throw new Exception(" must be 1 or below");} return true;} //trigger exception in a "try" block try{ checkNum(2);

//If the exception is thrown, this text will not be shown


echo 'If you see this, the number is 1 or below';} //catch exception
Copyright IBM Corporation 2012

Try, throw and catch


catch(Exception $e)
{

echo 'Message: ' .$e->getMessage();


} ?> The code above will get an error like this: Message: Value must be 1 or below

Copyright IBM Corporation 2012

Custom Exception
Creating a custom exception handler is quite simple.
We simply create a special class with functions that can be called when an exception occurs in PHP.

The class must be an extension of the exception class.


The custom exception class inherits the properties from PHP's exception class and you can add custom functions to it.
Copyright IBM Corporation 2012

Custom Exception
Lets create an exception class:
<?php class customException extends Exception{

public function errorMessage(){


//error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()

.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';


return $errorMsg;} }

$email = "someone@example...com";
Copyright IBM Corporation 2012

Custom Exception
try{ //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){

//throw exception if email is not valid


throw new customException($email);} }

catch (customException $e)


{ //display custom message

echo $e->errorMessage(); }
?>
Copyright IBM Corporation 2012

Multiple Exceptions
It is possible for a script to use multiple exceptions to check for multiple conditions.
It is possible to use several if..else blocks, a switch, or nest multiple exceptions.
<?php class customException extends Exception{ public function errorMessage(){ //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; return $errorMsg;}
Copyright IBM Corporation 2012

Multiple Exceptions
$email = "someone@example.com"; try{ //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email is not valid throw new customException($email);} //check for "example" in mail address

if(strpos($email, "example") !== FALSE){


throw new Exception("$email is an example e-mail"); }} catch (customException $e){

echo $e->errorMessage(); }
catch(Exception $e) { echo $e->getMessage(); }
Copyright IBM Corporation 2012

?>

Re-throwing Exceptions
Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way. It is possible to throw an exception a second time within a "catch" block. A script should hide system errors from users. System errors may be important for the coder, but is of no interest to the user. To make things easier for the user you can rethrow the exception with a user friendly message:

Copyright IBM Corporation 2012

Re-throwing Exceptions
<?php class customException extends Exception{ public function errorMessage(){ //error message $errorMsg = $this->getMessage().' is not a valid E-Mail address.'; return $errorMsg;} }

$email = "someone@example.com";
try{ try{

//check for "example" in mail address

Copyright IBM Corporation 2012

Re-throwing Exceptions
if(strpos($email, "example") !== FALSE) { //throw exception if email is not valid throw new Exception($email); } } catch(Exception $e) { //re-throw exception

throw new customException($email);}}


catch (customException $e){ //display custom message

echo $e->errorMessage();
} ?>
Copyright IBM Corporation 2012

Rules for exceptions


Code may be surrounded in a try block, to help catch potential exceptions .
Each try block or "throw" must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions. Exceptions can be thrown (or re-thrown) in a catch within a try block. A simple rule: If you throw something, you have to catch it.
Copyright IBM Corporation 2012

JAVASCRIPT
JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more. JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, Opera.

Copyright IBM Corporation 2012

WHAT IS JAVASCRIPT?
JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language (a scripting language is a lightweight programming language) A JavaScript consists of lines of executable computer code A JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation)

Copyright IBM Corporation 2012

How to Put a JavaScript Into an HTML Page?


<html> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html>

Copyright IBM Corporation 2012

JavaScript Variables
Variables are used to store data. A variable is a "container" for information you want to store. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value. Rules for variable names:
Variable names are case sensitive They must begin with a letter or the underscore character strname STRNAME (not same)

Copyright IBM Corporation 2012

Working with Variables & Data


A variable is a named element in a program that stores information. The following restrictions apply to variable names: the first character must be either a letter or an underscore character ( _ ) the remaining characters can be letters, numbers, or underscore characters variable names cannot contain spaces Variable names are case-sensitive. document.write(Year);
235
Copyright IBM Corporation 2012

Declaring a Variable
Before you can use a variable in your program, you need to declare a variable using the var command or by assigning the variable a value. Any of the following commands is a legitimate way of creating a variable named Month: var Month; var Month = December; Month = December;

Copyright IBM Corporation 2012

JavaScript Basic Examples


<script> document.write("Hello World!") </script> format text with HTML code - heading

<script> alert("Hello World!") </script>

Copyright IBM Corporation 2012

JavaScript Popup Boxes


Alert Box An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. <script> alert("Hello World!") </script>
Copyright IBM Corporation 2012

JavaScript Popup Boxes - 2


Confirm Box A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Copyright IBM Corporation 2012

JavaScript Popup Boxes - 3


Prompt Box A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK, the box returns the input value. If the user clicks "Cancel, the box returns null.
Copyright IBM Corporation 2012

Conditional Statements Examples


<script> x=3 if(x<0) { alert (negative) } else { alert (positive) } </script>
Copyright IBM Corporation 2012

Conditional Statements Examples


<script> x=3 if(x<0) { alert (negative) } else { alert (positive) } </script>
Copyright IBM Corporation 2012

Conditional Statements Examples


<script> x=3 if(x<0) { alert (negative) } else { alert (positive) } </script>
Copyright IBM Corporation 2012

Working with Program Loops


A program loop is a set of instructions that is executed repeatedly. There are two types of loops: loops that repeat a set number of times before quitting loops that repeat as long as a certain condition is met
244

Copyright IBM Corporation 2012

The For Loop


The For loop allows you to create a group of commands to be executed a set number of times through the use of a counter that tracks the number of times the command block has been run. Set an initial value for the counter, and each time the command block is executed, the counter changes in value. When the counter reaches a value above or below a certain stopping value, the loop ends.
245
Copyright IBM Corporation 2012

The For Loop Continued


for (start; condition; update)
{

JavaScript Commands
} start is the starting value of the counter condition is a Boolean expression that must be true for the loop to continue

Copyright IBM Corporation 2012

update specifies how the counter changes in value each time the command block is executed

For Loop

Copyright IBM Corporation 2012

For Loop

Copyright IBM Corporation 2012

Creating JavaScript Functions


function function_name(parameters) {
JavaScript commands

}
parameters are the values sent to the function (note: not all functions require parameters) { and } are used to mark the beginning and end of the commands in the function.

Copyright IBM Corporation 2012

Creating JavaScript Functions


Function names are case-sensitive. The function name must begin with a letter or underscore ( _ ) and cannot contain any spaces. There is no limit to the number of function parameters that a function may contain. The parameters must be placed within parentheses, following the function name, and the parameters must be separated by commas.

Copyright IBM Corporation 2012

Performing an Action with a Function


The following function displays a message with the current date:
function ShowDate(date) { document.write(Today is + date + <br>); } There is one line in the functions command block, which displays the current date along with a text string
Copyright IBM Corporation 2012

Performing an Action with a Function


To call the ShowDate function, enter:
var Today = 3/9/2013;

ShowDate(Today);
the first command creates a variable named Today and assigns it the text string, 3/9/2013 the second command runs the ShowDate function, using the value of the Today variable as a parameter result is Today is 3/9/2013
Copyright IBM Corporation 2012

Returning a Value from a Function


To use a function to calculate a value use the return command along with a variable or value.
function Area(Width, Length) { var Size = Width*Length; return Size;} the Area function calculates the area of a rectangular region and places the value in a variable named Size the value of the Size variable is returned by the function
Copyright IBM Corporation 2012

JavaScript Form Validation


JavaScript can be used to validate data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be: has the user left required fields empty?
has the user entered a valid e-mail address?

has the user entered a valid date?


has the user entered text in a numeric field?
Copyright IBM Corporation 2012

Required Fields
The function below checks if a field has been left empty.
If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:
function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } }
Copyright IBM Corporation 2012

Вам также может понравиться