Академический Документы
Профессиональный Документы
Культура Документы
Server
</html>
Client
HTTP Response
2
Copyright IBM Corporation 2012
Server
Script, or method
Client
HTTP Response
4
Copyright IBM Corporation 2012
Client-side
generally easier to implement may be prepared and implemented offline action occurs on the client side (browser)
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
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
Apache, a program running on the example.com computer,gets the message and reads the catalog.html file from the disk drive.
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.
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.
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
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
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.
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
$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;
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
Managing Variables
They enable you to check if certain variables exist, remove variables, and check variables truth values.
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
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.
Managing Variables
For example:
if (isset($name)) {
print $name is set'; }
This example will not generate any output, because isset() returns false.
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.
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.
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.
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.
Integers
240000
0xABCD
007
-100
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.
Floating-Point Numbers
3.14
+0.9e-2
-170000.5
54.6E42
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.
Double Quotes
"1234567890"
Strings can contain pretty much all characters. Some characters cant be written as is, however, and require special notation:
Double Quotes
Strings can contain pretty much all characters. Some characters cant be written as is, however, and require special notation:
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'
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
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.
Booleans
Consider the following code fragment:
$numerator = 1;
$denominator = 5;
if ($denominator == 0) { print "The denominator needs to be a non-zero number\n"; }
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.
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])
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
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.
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).
Numeric Operators
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;
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).
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.
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
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.
Comparison Operators
Comparison Operators
For the following two operators, automatic type conversions are not performed and, therefore, both the types and the values are compared.
Logical Operators
Logical operators first convert their operands to boolean values and then perform the respective comparison.
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
Negation Operators
Negation operators appear before their operand for example, !$var (! is the operator, $var is the operand).
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.
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;
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
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!
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.
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
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
String Manipulation
The strncmp() function compares two strings.
This function returns:
String Manipulation
Example
<?php echo strcmp("Hello world!","Hello world!"); ?> The output of the code above will be:
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
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!
String Manipulation
Example 2
<?php echo substr("Hello world!",6,5); ?> The output of the code above will be:
world
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!
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!
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
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.
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.
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 {
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) {
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).
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.
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;
}
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.
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++) {
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
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
return $GLOBALS[$name]; }
$num = 10;
$value = get_global_variable_value("num");
print $value;
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.
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.
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.
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
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 />
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
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
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.
Arrays
An array holding information about the colors of vegetables has vegetable names for keys and colors for values, shown below
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.
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';
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.
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.
Example prints:
There are 3 things for dinner.
Copyright IBM Corporation 2012
The foreach( ) construct lets you run a code block once for each element in an array.
Copyright IBM Corporation 2012
'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
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
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
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
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.
Sorting Arrays
Example
$dinner = array('Sweet Corn and Asparagus', 'Lemon Chicken','Braised Bamboo Fungus'); print "Before Sorting:\n"; foreach ($dinner as $key => $value) {
Sorting Arrays
Before Sorting:
$dinner: 0 Sweet Corn and Asparagus
$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( ).
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
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
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
$flavors = array('Japanese' => array('hot' => 'wasabi','salty' => 'soy sauce'),'Chinese' => array('hot' => 'mustard','pepper-salty' =>
Copyright IBM Corporation 2012
}
}
Copyright IBM Corporation 2012
PHP will see that "testFile.txt" does not exist and will create it after running this code.
Copyright IBM Corporation 2012
FileModes
The following table shows the different modes the file may be opened in.
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);
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
Bobby Bopper
Tracy Tanner
fwrite($fh, $stringData);
fclose($fh);
Copyright IBM Corporation 2012
Floppy Jalopy
Pointy Pinto
One character is equal to one byte. If you wanted to read the first five characters then you would use five as the integer.
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.
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
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;
Classes
function getName() { return $this->name; } }; $judy = new Person(); $judy->setName("Judy");
...
... // 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
}
}
Copyright IBM Corporation 2012
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.
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
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
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";
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.
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().
Static Methods
Heres an example:
class PrettyPrinter { static function printHelloWorld(){
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.
CLASS CONSTANTS
class MyColorEnumClass { const RED = "Red"; const GREEN = "Green";
}
print MyColorEnumClass::RED; $obj = new MyColorEnumClass();
$obj->printBlue();
This code prints "Red" followed by "Blue".
Copyright IBM Corporation 2012
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::__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.
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
Catch - A "catch" block retrieves an exception and creates an object containing the exception information
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.
Custom Exception
Lets create an exception class:
<?php class customException extends Exception{
$email = "someone@example...com";
Copyright IBM Corporation 2012
Custom Exception
try{ //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
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
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:
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{
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
echo $e->errorMessage();
} ?>
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.
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)
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)
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;
JavaScript Commands
} start is the starting value of the counter condition is a Boolean expression that must be true for the loop to continue
update specifies how the counter changes in value each time the command block is executed
For Loop
For Loop
}
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.
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
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