Chapter 3: PHP Language (II)
description
Transcript of Chapter 3: PHP Language (II)
Chapter 3: PHP Language (II)Chapter 3: PHP Language (II)
Tra
inin
g C
ou
rse, C
S, N
CTU
2
OverviewOverview
Arrays Flow Control – foreach Functions of Strings Object Oriented Exception Handling
Tra
inin
g C
ou
rse, C
S, N
CTU
3
Arrays (1)Arrays (1)
Something like cabinets.• You can put something in it.
• You can leave some empty space in.
Two types:• Indexed Arrays
Index # Value
• Associative Arrays Key Value
※ These two types can be mix-used,but No duplicate index numbers or keys are allowed!
a9x$
rAu\a
Tra
inin
g C
ou
rse, C
S, N
CTU
4
Arrays (2)Arrays (2)
Indexed Arrays• Index # Value
• The default start number of index is zero.
• Ex.
• To indicate one elements in array:$ary_name[idx_num] Ex. $ary[3]
0 1 2 3 4 5 6 7 8 9
a 9 x $ r A u \ a
Index
$ary[] Element of $ary[]with index=5
Tra
inin
g C
ou
rse, C
S, N
CTU
5
Arrays (3)Arrays (3)
• Construction Need no declaration. Two methods:
– Using 「 array()」 .
– Assign values directly.
$scores = array (80, 65, 89, 93);echo $scores[0]; // output 80echo $scores[1]; // output 65echo $scores[2]; // output 89echo $scores[3]; // output 93print_r ($scores);
Array(
[0] => 80[1] => 65[2] => 89[3] => 93
)
$scores[0] = 80;$scores[1] = 65;$scores[2] = 89;$scores[3] = 93;print_r ($scores);
print_r:Prints human-readable information about a variable
=$scores[] = 80;$scores[] = 65;$scores[] = 89;$scores[] = 93;
Tra
inin
g C
ou
rse, C
S, N
CTU
6
Arrays (4)Arrays (4)
Associative Arrays• Key Value
• Ex.
• To indicate one elements in array:$ary_name[key] Ex. $ary[‘John’]
Bob 80
John 65
Mary 89
Andy 93
Alice 80
Berry 95
Key$ary[]
Element of $ary[]with key=Alice
Tra
inin
g C
ou
rse, C
S, N
CTU
7
Arrays (5)Arrays (5)
• Construction Need no declaration. Two methods:
– Using 「 array( Key=>Value)」 .
– Assign Key & Value directly.
$scores = array('Bob'=>80, 'John'=>65, 'Mary'=>89, 'Andy'=>93 );
print_r ($scores);
Array(
[Bob] => 80[John] => 65[Mary] => 89[Andy] => 93
)
$scores['Bob'] = 80;$scores['John'] = 65;$scores['Mary'] = 89;$scores['Andy'] = 93;print_r ($scores);
Tra
inin
g C
ou
rse, C
S, N
CTU
8
Arrays (6)Arrays (6)
Accessing arrays• Reading
$ary_name[ idx_num or key ]
$scores = array (80, 65, 89, 'Andy'=>93);$c = $scores[2];$d = $scores['Andy'];echo $c; // output 89echo $d; // output 93echo $scores[1]; // output 65echo $scores['Andy']; // output 93
Tra
inin
g C
ou
rse, C
S, N
CTU
9
Arrays (7)Arrays (7)
• Adding/Modifying$ary_name[ idx_num or key ] = expression;
To change the index value while adding.
$scores = array (80, 65, 89, 'Andy'=>93);$scores[1] = 70;$scores['Andy'] = 95;$scores[3] = 86;echo $scores[1]; // output 70echo $scores['Andy']; // output 95echo $scores[3]; // 86print_r($scores);
Array(
[0] => 80[1] => 70[2] => 89[Andy] => 95[3] => 86
)
$scores = array (80, 65, 6=>89, 93);$scores[] = 88;print_r($scores);
Array(
[0] => 80[1] => 70[6] => 89[7] => 93[8] => 88
)
Tra
inin
g C
ou
rse, C
S, N
CTU
10
Arrays (8)Arrays (8)
• Deletingunset ( $ary_name[ idx_num or key ] );
$scores = array (80, 65, 89, 'Andy'=>93);unset ( $scores[1] );unset ( $scores['Andy'] );print_r($scores);
Array(
[0] => 80[2] => 89
)
$scores = array (80, 65, 89, 93);unset ( $scores[2] );$scores[2] = 76;print_r($scores);
Array(
[0] => 80[1] => 65[3] => 93[2] => 76
)
Tra
inin
g C
ou
rse, C
S, N
CTU
11
Arrays (9)Arrays (9)
Practicing• 1. Print the List Array
• 2. Print the Associate Array
• 3. Add Jaina to the Associate Array like
• 4. Edit John’s Score to 40 and Delete David’s Data.
Array( [0] => Charlie [1] => John [2] => David)
Array( [Charlie] => 84 [John] => 47 [David] => 29)
Array( [Charlie] => 84 [John] => 47 [David] => 29 [Jaina] => 77)
Array( [Charlie] => 84 [John] => 40 [Jaina] => 77)
http://tphp.cs.nctu.edu.tw/tphp/pr3-1_1.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-1_1.txt
http://tphp.cs.nctu.edu.tw/tphp/pr3-1_2.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-1_2.txt
http://tphp.cs.nctu.edu.tw/tphp/pr3-1_3.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-1_3.txt
http://tphp.cs.nctu.edu.tw/tphp/pr3-1_4.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-1_4.txt
Tra
inin
g C
ou
rse, C
S, N
CTU
12
Arrays (10)Arrays (10)
2-Dimentional Array• Something likes matrix.
• One array, each elementin it is also array.
• Notation$ary_name[key1][key2]
• Example$name_score[“David”][“score”] = “77”;
Not This
2067
3389
440
961
mv
kd
xer
xea
Tra
inin
g C
ou
rse, C
S, N
CTU
13
Arrays (11)Arrays (11)
Array Operators
Operator Description Example
+Union of two arrays.
※It appends the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
$a + $b
= Copy one away to another. ( to copy, not reference)※ $b = $a
== TRUE if two arrays have the same key/value pairs. $a == $b
===TRUE if two arrays have the same key/value pairs in the same order and of the same types.
$a === $b
!=, <> TRUE if two arrays are not equal. $a != $b
!== TRUE if two arrays are not identical. $a !== $b
Tra
inin
g C
ou
rse, C
S, N
CTU
14
Arrays (12)Arrays (12)
• Examples
$a = array("a" => "apple", "b" => "banana");$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
print_r ( $a + $b ); // Union of $a and $bprint_r ( $b + $a ); // Union of $b and $a
Array( [a] => apple [b] => banana [c] => cherry)Array( [a] => pear [b] => strawberry [c] => cherry)
$a = array( 70, 80); $b = array( 70, "80");echo ($a==$b) ? "equal" :"not equal"; // output equalecho ($a===$b)? "identical" : "not identical"; // output not identical
Array( [x] => 70 [y] => 80)Array( [y] => 80 [x] => 70)
$a = array( "x"=>70, "y"=>80);$b = array( "y"=>80, "x"=>70);print_r($a);print_r($b);echo ($a==$b) ? "equal" :"not equal"; // output equalecho ($a===$b)? "identical" : "not identical"; // output not indentical
Tra
inin
g C
ou
rse, C
S, N
CTU
15
Arrays (13)Arrays (13)
Functions for Arrays[Ref] http://www.php.net/manual/en/ref.array.php
• Getting Properties count(array) – getting array size (# of elements)
• Accessing array_pad(array) – Pad array to the specified length with a value. array_unique(array) – Returns a new array without duplicate values. array_reverse(array) – Return an array with elements in reverse order. array_keys(array) – Return all the keys of an array. array_values(array) – Return all the values of an array.
Tra
inin
g C
ou
rse, C
S, N
CTU
16
Arrays (14)Arrays (14)
• Using Array’s Internal Pointer reset, next, prev, end
– Moving Internal Pointer
current, key– Get value/key of the record pointed by I.P.
list(var1, var2, …) – Assign variables as if they were an array.$box = array ( 200, 80, 70);
list ($x, $y, $z) = $box; //$x=200, $y=80, $z=70
each(array)– Return the current key and value pair from an array, advance the array
cursor.
$a = array ( 60, 50, 40);while (list ($k, $v) = each($a)) echo "$k = $v";
0 = 60 1 = 50 2 = 40
Tra
inin
g C
ou
rse, C
S, N
CTU
17
Arrays (15)Arrays (15)
• Sorting In Arrays sort, rsort
– Sort an array
asort, arsort– Sort an array and maintain index association
ksort, krsort– Sort an array by key. (will also keep index association)
Example
echo "<br />\n";$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");$s = $fruits; sort($s);$a = $fruits; asort($a);$k = $fruits; ksort($k);print_r($s);print_r($a);print_r($k);
Array([0] => apple[1] => banana[2] => lemon[3] => orange)
Array([c] => apple[b] => banana[d] => lemon[a] => orange)
Array([a] => orange[b] => banana[c] => apple[d] => lemon)
Tra
inin
g C
ou
rse, C
S, N
CTU
18
Arrays (16)Arrays (16)
• Searching In Arrays in_array($value, $array, [$bool])
– Return TRUE if value exists in array.
array_search ($value, $array, [$bool])– Return index/key.
Example
$os = array("Mac", "NT", "Irix", "Linux");if (in_array("Irix", $os)) echo "Got Irix";if (in_array("mac", $os)) echo "Got mac";
Got Irix
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;$key = array_search(‘yellow', $array); // $key = false;
Tra
inin
g C
ou
rse, C
S, N
CTU
19
Arrays (17)Arrays (17)
Practicing• 1. Sort the score list and Print it (from high to low).
• 2. Find if 77, 32 are in the list.
7478257595581211469306038351006961024256557602342773299550
http://tphp.cs.nctu.edu.tw/tphp/pr3-2_1.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-2_1.txthttp://tphp.cs.nctu.edu.tw/tphp/pr3-2_2.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-2_2.txt
Tra
inin
g C
ou
rse, C
S, N
CTU
20
Flow Control – foreach (1)Flow Control – foreach (1)
How to get every keys & values in an array?• “print_r” only print it out, not accessible.
• How about this?
Only suitable for indexed arrays, andnot allowing “holes” in arrays.
• Better one
But too complex
for ( $i = 0; $ary[$i] != NULL; $i++){ … // $i is index, $ary[$i] is value}
reset($ary);while (($v=current($ary))!=NULL){ $k = key($ary); … // $k is key, $v is value next($ary);}
Tra
inin
g C
ou
rse, C
S, N
CTU
21
Flow Control – foreach (2)Flow Control – foreach (2)
• Rewrite to “for loop”
Seems better, but… I don’t like it.
• Using foreach
Syntax:
foreach ($array as $key => $value) {
…
}
foreach ($array as $value) { // when $key not needed
…
}
for(reset($ary);$v=current($ary);next($ary)){ $k = key($ary); … // $k is key, $v is value}
foreach ($ary as $k => $v){ … // $k is key, $v is value}
Tra
inin
g C
ou
rse, C
S, N
CTU
22
Flow Control – foreach (3)Flow Control – foreach (3)
• Another approach – using list & each
Syntax:
reset($array);
while ( list($key, $value)=each($array)) {
…
}
reset($array);
while ( list(, $value)=each($array)) { // when $key not needed
…
}
reset($ary);while (list($k, $v)=each($ary)) { … // $k is key, $v is value}
Tra
inin
g C
ou
rse, C
S, N
CTU
23
Flow Control – foreach (4)Flow Control – foreach (4)
Practicing• 1. Use foreach to dump the score list.
• 2. Use while to dump the score list.
• 3. Use foreach to dump the score list twice.
• 4. Use while to dump the score list twice.
Array( [Charlie] => 84 [John] => 47 [David] => 29 [Jaina] => 77)
http://tphp.cs.nctu.edu.tw/tphp/pr3-3_1.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-3_1.txt
http://tphp.cs.nctu.edu.tw/tphp/pr3-3_2.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-3_2.txt
http://tphp.cs.nctu.edu.tw/tphp/pr3-3_3.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-3_3.txt
http://tphp.cs.nctu.edu.tw/tphp/pr3-3_4.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-3_4.txt
Tra
inin
g C
ou
rse, C
S, N
CTU
24
Functions of Strings (1)Functions of Strings (1)
Strings – Characters connected, quoted with ‘’ or “” Useful functions
[Ref] http://www.php.net/manual/en/ref.strings.php
• Getting Properties strlen(string) – Get string length.
Example
$str = 'abcdef';echo strlen($str); // 6
$str = ' ab cd ';echo strlen($str); // 7
Tra
inin
g C
ou
rse, C
S, N
CTU
25
Functions of Strings (2)Functions of Strings (2)
• Transformation trim, ltrim, rtrim, chop – Strip whitespace of a string.
– trim – From the beginning and end of a string.
– ltrim – From the beginning of a string.
– rtrim – From the end of a string.
– chop – The same with rtrim.
strtolower, strtoupper – Make a string lowercase/uppsercase. strrev – Reverse a string. str_repeat(string, times) – Repeat string $times times.
Example
$text = "\t\tA few words :) ... ";echo trim($text); // "A few words :) ..."echo trim($text, " \t."); // “A few words :)"
$str = “HELLO";$str = strtolower($str);echo $str; // hello
echo strrev("Hello world!"); // outputs "!dlrow olleH"
echo str_repeat("-=", 5); // outputs “-=-=-=-=-=“
Tra
inin
g C
ou
rse, C
S, N
CTU
26
Functions of Strings (3)Functions of Strings (3)
• Searching/Tokenizing substr – Return part of a string. strpos, strrpos – Find position of first/last occurrence of a string. strstr, stristr, strchr, strrchr
– Return remaining sub-string while matching first/last occurrence of a string.
substr_count – Count the number of substring occurrences.
Example
echo substr('abcdef', 1); // bcdefecho substr('abcdef', 1, 3); // bcdecho substr('abcdef', 0, 4); // abcdecho substr('abcdef', 0, 8); // abcdefecho substr('abcdef', -1, 1); // f
$newstring = 'abcdef';$pos = strpos($newstring, 'a'); // $pos = 0
$email = '[email protected]';$domain = strstr($email, '@');echo $domain; // prints @example.com
$text = 'This is a test';echo substr_count($text, 'is'); // 2
Tra
inin
g C
ou
rse, C
S, N
CTU
27
Functions of Strings (4)Functions of Strings (4)
Practicing
• 1. Find length of this String.
• 2. Strip head/end whitespace of this String and show length.
• 3. Make this String to uppercase and print it.
• 4. Print first 20 character of this string.
• 5. Find ‘enables’ first occurrence position.
“ WaSP issues an open invitation to work with Assistive Technology Vendors to help ensure greater support for standards-based web development techniques in software that enables access for millions of people worldwide. “
http://tphp.cs.nctu.edu.tw/tphp/pr3-4_1.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-4_1.txt
http://tphp.cs.nctu.edu.tw/tphp/pr3-4_2.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-4_2.txt
http://tphp.cs.nctu.edu.tw/tphp/pr3-4_3.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-4_3.txt
http://tphp.cs.nctu.edu.tw/tphp/pr3-4_4.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-4_4.txt
http://tphp.cs.nctu.edu.tw/tphp/pr3-4_5.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-4_5.txt
http://tphp.cs.nctu.edu.tw/tphp/pr3_4_string.txt
Tra
inin
g C
ou
rse, C
S, N
CTU
28
Functions of Strings (5)Functions of Strings (5)
Further Study: Regular Expression• Functions
ereg, eregi– Regular expression match.
split, spliti– Split string into array by regular expression.
ereg_replace, eregi_replace– Replace regular expression.
preg_*– Using perl-compatible regular expression.
Tra
inin
g C
ou
rse, C
S, N
CTU
29
Functions of Strings (6)Functions of Strings (6)
• Example
$date = “2006-11-12”;if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) { echo "$regs[3].$regs[2].$regs[1]"; // outputs “12.11.2006” } else { echo "Invalid date format: $date";}
$date = "04/30/1973";list($month, $day, $year) = split('[/]', $date);echo "Month: $month, Day: $day; Year: $year<br />\n";// outputs “Month:04, Day: 30, Year: 1973”;
$string = "This is a test";echo str_replace(" is", " was", $string); // outputs “This was a test”echo ereg_replace("( )is", "\\1was", $string); // outputs “This was a test”echo ereg_replace("(( )is)", "\\2was", $string); // outputs “This was a test”
Tra
inin
g C
ou
rse, C
S, N
CTU
30
Object Oriented (1)Object Oriented (1)
PHP supports OOP (Object-Oriented Programming)
Basic Properties of Object• State member data• Behavior member functions• Identity object name (like variable name)
OOP• Languages that supports 3 object-oriented characteristics.
Encapsulation– Encapsulate variables & functions to be an object.
Inheritance– Reuse existing objects.
Polymorphism– Using same code handling different types of data types.
variables
method
method
methodmethod
Tra
inin
g C
ou
rse, C
S, N
CTU
31
Object Oriented (2)Object Oriented (2)
Class and Object• Class
The blueprint of object Contains the definition of “member data” and “member functions”
• Defining Classesclass classname {
var $var1;
var $var2, $var3;
function __construct ($invar1, $invar2, …){ …}
function __destruct () {…}
function member_func ($invarx, $invary, …) {…}
}
• Creating Objects$obj = new classname($arg1, $arg2, …);
Tra
inin
g C
ou
rse, C
S, N
CTU
32
Object Oriented (3)Object Oriented (3)
• Example
class Student { var $id, $name; function setid($newid){ //do nothing }}
$s1 = new Student();print_r ($s1);
student Object(
[id] =>[name] =>
)
Tra
inin
g C
ou
rse, C
S, N
CTU
33
Object Oriented (4)Object Oriented (4)
• Accessing member data & Calling member function Inner object
Member data: $this -> varname
Member function: $this -> member_fun($arg1, $arg2, …) Out of object
Member data: $obj -> varname
Member function: $obj -> member_fun($arg1, $arg2, …)
Tra
inin
g C
ou
rse, C
S, N
CTU
34
Object Oriented (5)Object Oriented (5)
• Example
class Student { var $id, $name; function setid($newid){ $this->id = $newid; } function getid(){ return $this->id; }}
$s1 = new Student(); $s2 = new Student();
$s1->id = "9412345";echo "Student1 ID:", $s1->id; // output 9412345
$s2->setid("9654321");echo "Student2 ID:", $s2->getid(); // output 9654321
Tra
inin
g C
ou
rse, C
S, N
CTU
35
Object Oriented (6)Object Oriented (6)
• Constructor and Destructor Constructor
– The initial function object generated.
function __constructor ($invar1, $invar2, …) { … } Destructor
– The final function before object die.
function __destructor () { … } There are no return values in both constructors and destructors.
Tra
inin
g C
ou
rse, C
S, N
CTU
36
Object Oriented (7)Object Oriented (7)
• Example
class MyDestructableClass { function __construct() { print "In constructor\n"; $this->name = "MyDestructableClass"; }
function __destruct() { print "Destroying " . $this->name . "\n"; }}
$obj = new MyDestructableClass();
In constructorDestroying MyDestructableClass
Tra
inin
g C
ou
rse, C
S, N
CTU
37
Object Oriented (8)Object Oriented (8)
• Visibility of member data/functions private
– Only visible inner class itself.
public– Visible everywhere.
protected– Visible in itself and classes inherit this class.
Tra
inin
g C
ou
rse, C
S, N
CTU
38
Object Oriented (9)Object Oriented (9)
• Example
class MyClass{ public $public = 'Public'; protected $protected = 'Protected'; private $private = 'Private';
function printHello() { echo $this->public; echo $this->protected; echo $this->private; }}
$obj = new MyClass();echo $obj->public; // Worksecho $obj->protected; // Fatal Errorecho $obj->private; // Fatal Error$obj->printHello(); // Shows Public, Protected and Private
class MyClass2 extends MyClass{ function printHello() { echo $this->public; echo $this->protected; echo $this->private; }}
$obj2 = new MyClass2();echo $obj->public; // Worksecho $obj2->private; // Undefined (not error)echo $obj2->protected; // Fatal Error$obj2->printHello(); // Shows Public, Protected, not Private
Tra
inin
g C
ou
rse, C
S, N
CTU
39
Object Oriented (10)Object Oriented (10)
• Class constant Syntax:
class classname {
const CONSTNAME = value;
} Accessing
– Inner object
» self ::CONSTNAME– Out of object
» classname::CONSTNAME
Tra
inin
g C
ou
rse, C
S, N
CTU
40
Object Oriented (11)Object Oriented (11)
• Static member data/functions Syntax:
class classname {
public static $VARIABLE = value;
public static function METHOD() {
………
}
} Accessing
– Inner object
» self::$VARIABLE
» self::METHOD()– Out of object
» classname::$VARIABLE
» classname::METHOD()
Tra
inin
g C
ou
rse, C
S, N
CTU
41
Object Oriented (12)Object Oriented (12)
• Exampleclass Foo{ public static $my_static = 'foo';
public function staticValue() { return self::$my_static; }}class Bar extends Foo{ public function fooStatic() { return parent::$my_static; }}print Foo::$my_static . "\n";$foo = new Foo();print $foo->staticValue() . "\n";print $foo->my_static . "\n"; // Undefined "Property" my_static // $foo::my_static is not possibleprint Bar::$my_static . "\n";$bar = new Bar();print $bar->fooStatic() . "\n";
class Foo { public static function aStaticMethod() { // ... }}
Foo::aStaticMethod();
class MyClass{ const constant = 'constant value';
function showConstant() { echo self::constant . "\n"; }}echo MyClass::constant . "\n";$class = new MyClass();$class->showConstant();// echo $class::constant; is not allowed
Tra
inin
g C
ou
rse, C
S, N
CTU
42
Object Oriented (13)Object Oriented (13)
Priacticing• Make a Class “Book” who has members: “code”, “title”, “author”, “
price”. Make a constructor function, a function BookCounts() to get how many books there and a function showBook() to print information of a Book. The Book Maximum num is 50.
http://tphp.cs.nctu.edu.tw/tphp/pr3-5.phphttp://tphp.cs.nctu.edu.tw/tphp/pr3-5.txt
Tra
inin
g C
ou
rse, C
S, N
CTU
43
Object Oriented (14)Object Oriented (14)
Further Study• Inheritance
class classname extends parent_class {
…
}
• Polymorphism abstract & interface
Tra
inin
g C
ou
rse, C
S, N
CTU
44
Exception Handling (1)Exception Handling (1)
Exceptions (Errors)• Reason
Environmental Programming
• Levels Parse Errors Fatal Errors Warnings Notices
Tra
inin
g C
ou
rse, C
S, N
CTU
45
Exception Handling (2)Exception Handling (2)
Exception Handling• Error Reporting
Setting what will be reported:error_reporting ( ERR1 | ERR2 | … );
ERRORS ( Predefined Constants)– E_ALL
– E_ERROR, E_WARNING, E_PARSE, E_NOTICE
– E_CORE_ERROR, E_CORE_WARNING
– E_COMPILE_ERROR, E_COMPILE_WARNING
– E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
– E_STRICT ( PHP 5.0)≧– E_RECOVERABLE_ERROR ( PHP 5.2)≧
Tra
inin
g C
ou
rse, C
S, N
CTU
46
Exception Handling (3)Exception Handling (3)
• Error Handler Setting who (function) will handle errors:
set_error_handler(‘handlername’);
function handlername($type, $msg, $file, $line) {
// $type is error level
// $msg is error info
// $file is the php filename executed
// $line is the line number of code when error happened.
}
Tra
inin
g C
ou
rse, C
S, N
CTU
47
Exception Handling (4)Exception Handling (4)
• Logging Errors Error handler can keep logs somewhere he want. Setting where to keep logs:
error_log($msg, OUTPUT_TYPE, $target); OUTPUT_TYPE
– 0 Log to system log
– 1 Log mailed to $target (should be an email address)
– 3 Log to $target (should be a file)
Tra
inin
g C
ou
rse, C
S, N
CTU
48
Exception Handling (5)Exception Handling (5)
• User Level Errors User can create some errors in the programs. Generating user level error:
trigger_error($msg, ERROR); ERROR available
– E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
Tra
inin
g C
ou
rse, C
S, N
CTU
49
Exception Handling (6)Exception Handling (6)
• Example// set the error reporting level for this scripterror_reporting(E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE);// error handler functionset_error_handler(“myErrorHandler”);function myErrorHandler($errno, $errstr, $errfile, $errline) { switch ($errno) { case E_USER_ERROR: echo "<b>My ERROR</b> [$errno] $errstr<br />\n"; echo " Fatal error in line $errline of file $errfile"; echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n"; echo "Aborting...<br />\n"; exit(1); break; case E_USER_WARNING: echo "<b>My WARNING</b> [$errno] $errstr<br />\n"; break; case E_USER_NOTICE: echo "<b>My NOTICE</b> [$errno] $errstr<br />\n"; break; default: echo "Unknown error type: [$errno] $errstr<br />\n"; break; }}
Tra
inin
g C
ou
rse, C
S, N
CTU
50
Exception Handling (7)Exception Handling (7)
• Example 2// Send notification through the server log if we can not// connect to the database.if (!Ora_Logon($username, $password)) { error_log("Oracle database not available!", 0);}
// Notify administrator by email if we run out of FOOif (!($foo = allocate_new_foo())) { error_log("Big trouble, we're all out of FOOs!", 1, "[email protected]");}
// other ways of calling error_log():error_log("You messed up!", 2, "127.0.0.1:7000");error_log("You messed up!", 2, "loghost");error_log("You messed up!", 3, "/var/tmp/my-errors.log");
if (assert($divisor == 0)) { trigger_error("Cannot divide by zero", E_USER_ERROR);}
Tra
inin
g C
ou
rse, C
S, N
CTU
51
Exception Handling (8)Exception Handling (8)
Further Study:• Exception Objects (PHP 5.0)≧
Exception handling likes java, VB.NET, C#, …etc. Generating Exception
throw ExceptionObject;
Handling Exceptiontry{
… // what to do
}catch ( ExceptionClass $exception) {
… // code to handle exceptions
}
Tra
inin
g C
ou
rse, C
S, N
CTU
52
Q&AQ&A