7/28/2019 Slides Beamer 2x2
1/18
Berner Fachhochschule-Technik und Informatik
Web Programming
2) PHP Basic Syntax
Dr. E. Benoist
Fall Semester 2012/2013
Web Programming 2) PHP Basic Syntax
1
Presentation : What is PHP ?
PHP stands for PHP Hypertext Preprocessor
Scripting Language linked with Apache Server
Can be installed as an Apache Module or as CGI Syntax borrowed from C, Java and Perl
Write Dynamically generated pages quickly.
Generate HTML on the Fly for questioning Data Bases
Generate Images on the Fly.
Web Programming 2) PHP Basic Syntax
Introduction: What is PHP ? 2
Basic concepts of PHP Introduction
What is PHP ?Starting with PHP
Basic SyntaxNumbersStringsArrays
VariablesConstantsControl StructuresInclude files
Programming in PHPFunctionsObject Oriented Programming
Web Programming 2) PHP Basic Syntax
Introduction: What is PHP ? 3
Our First PHP File: A php file is an HTML file containing PHP instructions.
You can use four styles to include php information in a PHPfile. The ASP tags are only recognized if php is compiled withthe option --enable asp-tags.
Escaping from HTML
echo (Javascriptlike syntax (for HTML editors));
7/28/2019 Slides Beamer 2x2
2/18
Instruction separation
Generally an instruction terminate with a ; but theclosing tag also implies the end of the statement
Web Programming 2) PHP Basic Syntax
Introduction: Starting with PHP 5
Comments PHP supports C, C++ (=Java) and Unix shell style
comments
7/28/2019 Slides Beamer 2x2
3/18
Strings Two sets of delimiters and (like in perl)
Delimiters quote : The text is a string Delimiters double-quote : variables within the string will be
expanded (subject to some parsing limitations). As in C andPerl, the backslash (\) character can be used in specifying
special characters:# Strict delimiter$str1=toto\n;# Allows interpolation$str2=toto\n;echo $str1;echo $str2;
Output:
toto\ntoto
Web Programming 2) PHP Basic Syntax
Basic Syntax: Strings 9
Other string examples$name=Emmanuel;$str1 = Hello $name;$str2 = Hello $name;echo $str1; // The name is replacedecho $str2; // $name appears on the screen
echo
\n;$str3 = hello \n;$str4 = world
\n;echo $str3;echo $str4;echo $str3.$str4;
Output (in the browser)
Hello EmmanuelHello $namehello worldhello world
Web Programming 2) PHP Basic Syntax
Basic Syntax: Strings 10
Strings (Cont.)
Escaped characters
Sequence meaning
\n linefeed\r carriage return\t horizontal tab\\ backslash
\$ dollar sign\ double quote\[0 7]{1, 3} the sequence of characters matching
the regular expression is a characterin octal notation
\x[0 9A Fa f]{1, 2} the sequence of characters matchingthe regular expression is a characterin hexadecimal notation
Web Programming 2) PHP Basic Syntax
Basic Syntax: Strings 11
Here dochere doc syntax (
7/28/2019 Slides Beamer 2x2
4/18
More with Strings
Strings may be concatenated using the . (dot) operator. Notethat the + (addition) operator will not work for this.Characters within strings may be accessed by treating the string asa numerically-indexed array of characters.
/ Assigning a string. /$str = This is a string;
/ Appending to it. /$str = $str . with some more text;/ Another way to append, includes an escaped newline. /$str .= and a newline at the end.\n;/ This string will end up being Number: 9/$num = 9;$str =
Number: $num
;/ This one will be Number: $num/$num = 9;$str =Number: $num
;/ Get the first character of a string/$str = This is a test.;$first = $str[0];/ Get the last character of a string. /$str = This is still a test.;$last = $str[strlen($str)1];Web Programming 2) PHP Basic Syntax
Basic Syntax: Strings 13
String conversion
When a string is evaluated as a numeric value, theresulting value and type are determined as follows.
The string will evaluate as a double if it contains any of thecharacters ., e, or E. Otherwise, it will evaluate as aninteger.
The value is given by the initial portion of the string. If thestring starts with valid numeric data, this will be the valueused. Otherwise, the value will be 0 (zero).Valid numeric data is an optional sign, followed by one or moredigits (optionally containing a decimal point), followed by anoptional exponent.The exponent is an e or E followed by one or more digits.
When the first expression is a string, the type of the variablewill depend on the second expression.
Web Programming 2) PHP Basic Syntax
Basic Syntax: Strings 14
String conversion(Cont.)
$foo = 1 + 10.5; // $foo is double (11.5)$foo = 1 + 1.3e3; // $foo is double (1299)$foo = 1 + bob1.3e3; // $foo is integer (1)$foo = 1 + bob3; // $foo is integer (1)
$foo = 1 + 10 Small Pigs; // $foo is integer (11)$foo = 1 + 10 Little Piggies; // $foo is integer (11)$foo = 10.0 pigs + 1; // $foo is integer (11)$foo = 10.0 pigs + 1.0; // $foo is double (11)
Web Programming 2) PHP Basic Syntax
Basic Syntax: Strings 15
Single Dimension Arrays
PHP does not make a great difference between arrays (indexedwith numbers) and hash tables (indexed with strings).
// You can initialize an empty array$toto = array();
// Or just define its elements
$a[0] = abc;$a[1] = def;$b[foo] = 13;
// It is possible to insert elements :$a[] = hello; // $a[2] == hello$a[] = world; // $a[3] == world
Web Programming 2) PHP Basic Syntax
Basic Syntax: Arrays 16
7/28/2019 Slides Beamer 2x2
5/18
Multi-Dimensional Arrays
PHP allows multidimensional arrays
$a[1] = $f; # one dimensional examples$a[foo] = $f;
$a[1][0] = $f; # two dimensional$a[foo][2] = $f; # (you can mix numeric and associative indices)$a[3][bar] = $f; # (you can mix numeric and associative indices)
$a[foo][4][bar][0] = $f; # four dimensional!
Web Programming 2) PHP Basic Syntax
Basic Syntax: Arrays 17
Multi-Dimensional Arrays(Cont.)
Initialization
# Example 1:$a[color] = red;$a[taste] = sweet;
$a[shape] = round;$a[name] = apple;$a[3] = 4;# Example 2:$a = array(
color => red,taste => sweet,shape => round,name => apple,3 => 4
);
Web Programming 2) PHP Basic Syntax
Basic Syntax: Arrays 18
Multi-Dimensional Arrays(Cont)
Initialization of a bidimentional array:
$a = array(apple => array( color => red,
taste => sweet,shape => round ),
orange => array( color => orange,taste => sweet,shape => round),
banana => array( color => yellow,taste => pastey,shape => bananashaped));
echo $a[apple][taste]; # will output sweet
Web Programming 2) PHP Basic Syntax
Basic Syntax: Arrays 19
Type Juggling
PHP does not require (or support) explicit typedefinition in variable declaration;
A variables type is determined by the context in which thatvariable is used.
That is to say, if you assign a string value to variable $var,$var becomes a string. If you then assign an integer value to$var, it becomes an integer.
$foo = 1; // $foo is string (ASCII 49)$foo += 1; // $foo is now an integer (2)$foo = $foo + 1.3; // $foo is now a double (3.3)$foo = 5 + 10 Little Piggies; // $foo is integer (15)$foo = 5 + 10 Small Pigs; // $foo is integer (15)
Web Programming 2) PHP Basic Syntax
Basic Syntax: Variables 20
7/28/2019 Slides Beamer 2x2
6/18
Type casting
To change the type of an element you have to give thedesired type in parentheses
// Casting types
$a1= 10; // $a1 is an integer$a2 = (double)$a1; // $a2 is a double
(int), (integer) - cast to an integer (real), (double), (float) - cast to double (string) - cast to string (array) - cast to array (object) - cast to object
Web Programming 2) PHP Basic Syntax
Basic Syntax: Variables21
Variables : Basics Variables in PHP are represented by a dollar sign
followed by the name of the variable. The variable nameis case-sensitive.
$var = Bob;$Var = Joe;echo $var, $Var; // outputs Bob, Joe
$4site = not yet; // invalid; starts with a number$ 4site = not yet; // valid; starts with an underscore$tayte = mansikka; // vali d; a is ASCII 228.
Variables assigned by reference
$foo = Bob; // Assign the value Bob to $foo$bar = &$foo; // Reference $foo via $bar.$bar = My name is $bar; // Alter $bar...echo $foo; // $foo is altered too.echo $bar;
Web Programming 2) PHP Basic Syntax
Basic Syntax: Variables22
Variables (Cont.)
Only named variables may be assigned by reference
$foo = 25;$bar = &$foo; // This is a valid assignment.$bar = &(24 7); // Invalid; references an unnamed expression.
function test() {return 25;}$bar = &test(); // Invalid.
Web Programming 2) PHP Basic Syntax
Basic Syntax: Variables 23
Variables Scope Scope = context within a variable is defined.
$a = 1;function Test(){ / reference to local scope variable/
echo Value : $a \n;}Test();
Output : Value :
Global variables$a = 1; $b = 1;function Test2(){
global $a, $b;$b = $a + $b;
}Test2(); echo $b;
Output: 2
Web Programming 2) PHP Basic Syntax
Basic Syntax: Variables 24
7/28/2019 Slides Beamer 2x2
7/18
Variables (Cont.) Static variables
The value of a static variable exists only in a local function scope, butremains the same for many execution
// Useless Function it does nothingfunction Test3(){
$a = 0;
echo $a;$a++;
}// This function allows us to increment a counterfunction Test4(){
static $a = 0;echo $a;$a++;
}Test3();Test3();Test3();echo ;;Test4();Test4();Test4();
Output : 000;012
Web Programming 2) PHP Basic Syntax
Basic Syntax: Variables25
Variable variablesSometimes it is convenient to be able to have variable variable names.That is, a variable name which can be set and used dynamically.
$a = hello; // How to set a normal variable
A variable variable takes the value of a variable and treats that as thename of a variable.In the above example, hello, can be used as the name of a variable byusing two dollar signs. i.e.
$$a = world;
At this point two variables have been defined and stored in the PHPsymbol tree: $a with contents hello and $hello with contents world.Therefore, this statement:
echo $a ${$a};echo $a $hello; // Produce exactly the same output// Output is : hello world
Web Programming 2) PHP Basic Syntax
Basic Syntax: Variables26
Constants
There exists predefine constants, such as TRUE, FALSE,PHP VERSION or PHP OS.Moreover can you define your own constants using thedefine() function.
Web Programming 2) PHP Basic Syntax
Basic Syntax: Constants 27
Constants (Cont.)
Constants FILE and LINE
FILE : The name of the script file presently being parsed. LINE : The number of the line within the current script file
which is being parsed.
Web Programming 2) PHP Basic Syntax
Basic Syntax: Constants 28
7/28/2019 Slides Beamer 2x2
8/18
Control Structures : IF
C like IF
if($a>$b){ echo $a is strictly greater that $b
\n;}elseif($a==$b){ echo $a is equal to $b
\n;}else{ echo $a is strictly smaller that $b
\n;
}
Output : 12 is strictly smaller that 13
Embaded in HTML code
a is strictly greater that b
a is equal to b
a is strictly smaller that b
Output : a is strictly smaller that b
Web Programming 2) PHP Basic Syntax
Basic Syntax: Control Structures29
Control Structures : WHILE
C like
$i=1;while ($i
7/28/2019 Slides Beamer 2x2
9/18
Foreach
PHP includes a foreach construct, much like Java 1.5 and someother languages. This simply gives an easy way to iterate overarrays.
foreach(array expression as $value) statementforeach(array expression as $key => $value) statement
The first form loops over the array given by array expression.On each loop, the value of the current element is assigned to$value and the internal array pointer is advanced by one (soon the next loop, youll be looking at the next element).
The second form does the same thing, except that the currentelements key will be assigned to the variable $key on eachloop.
Web Programming 2) PHP Basic Syntax
Basic Syntax: Control Structures33
Foreach (Cont.)
Visit all the values of an Array
foreach ($arr as $value) {echo Value: $value
\n;
}
Visit the values and the keys
foreach ($arr as $key => $value) {echo Key: $key; Value:
$value
\n;
}
Web Programming 2) PHP Basic Syntax
Basic Syntax: Control Structures34
Foreach : Example/ foreach example 1: value only/$a = array (1, 2, 3, 17);foreach ($a as $v) {
print Current value of \$a: $v.\n;}/ foreach example 2: value (with key printed for illustration) /$a = array (1, 2, 3, 17);$i = 0; / for illustrative purposes only /foreach($a as $v) {
print \$a[$i] => $v.\n;$i++;
}/ foreach example 3: key and value /$a = array (
one => 1,two => 2,three => 3,seventeen => 17
);foreach($a as $k => $v) {
print \$a[$k] => $v.\n;}
Web Programming 2) PHP Basic Syntax
Basic Syntax: Control Structures 35
Breakbreak ends execution of the current for, while, or switch structure.break accepts an optional numeric argument which tells it how many nestedenclosing structures are to be broken out of.
$arr = array (one, two, three, four, stop, five);while (list (, $val) = each ($arr)) {
if ($val == stop) {break; / You could also write break 1; here. /
}echo $val
\n;
}
/ Using the optional argument. /$i = 0;
while (++$i) {switch ($i) {
case 5:echo At 5
\n;break 1; / Exit only the switch. /
case 10:echo At 10; quitting
\n;break 2; / Exit the switch and the while. /
default:break;
}}
Web Programming 2) PHP Basic Syntax
Basic Syntax: Control Structures 36
7/28/2019 Slides Beamer 2x2
10/18
Continue continue is used within looping structures to skip the
rest of the current loop iteration and continue executionat the beginning of the next iteration.while (list ($key, $value) = each ($arr)) {
if (!($key % 2)) { // skip odd memberscontinue;
}do something odd ($value);
}$i = 0;while ($i++ < 5) {
echo Outer
\n;while (1) {
echo Middle
\n;while (1) {
echo Inner
\n;continue 3;
}echo This never gets output.
\n;
}echo Neither does this.
\n;
}
Web Programming 2) PHP Basic Syntax
Basic Syntax: Control Structures37
Switch
The switch statement is similar to a series of IF statements on thesame expression.
switch ($i) {case 0:
case 1:case 2:
print i is less than 3 but not negative;break;
case 3:print i is 3;
}
Web Programming 2) PHP Basic Syntax
Basic Syntax: Control Structures38
require()
The require() statement replaces itself with thespecified file, much like the C preprocessors #includeworks.require() and require once() produce a fault when theresource is not available.
// imports all the functions and classes
require (file.php);
// This file is loaded only once (even if required many times)require once(test.php);
The include() statement includes and evaluates thespecified file.Almost the same without creating an error.
Web Programming 2) PHP Basic Syntax
Basic Syntax: Include files 39
User defined functions
Example
function foo ($arg 1, $arg 2, ..., $arg n) {echo Example function.\n;return $retval;
}
Arguments
function takes array($input) {echo $input[0] + $input[1] = , $input[0]+$input[1];
}
Web Programming 2) PHP Basic Syntax
Programming in PHP: Functions 40
7/28/2019 Slides Beamer 2x2
11/18
User defined functions(Cont.)
Making arguments be passed by reference
By default, function arguments are passed by value.
If you wish to allow a function to modify its arguments, youmust pass them by reference.
If you want an argument to a function to always be passed byreference, you can prepend an ampersand (&) to theargument name in the function definition:
function add some extra(&$string) {$string .= and something extra.;
}$str = This is a string, ;add some extra($str);echo $str; // outputs This is a string, and something extra.
Web Programming 2) PHP Basic Syntax
Programming in PHP: Functions 41
User defined functions(Cont.)
If you wish to pass a variable by reference to a function which doesnot do this by default, you may prepend an ampersand to theargument name in the function call:
function foo ($bar) {
$bar .= and something extra.;}
$str = This is a string, ;foo ($str);echo $str; // outputs This is a string, foo (&$str);echo $str; // outputs This is a string, and something extra.
Web Programming 2) PHP Basic Syntax
Programming in PHP: Functions 42
Variable functionsPHP supports the concept of variable functions. This means thatif a variable name has parentheses appended to it, PHP will lookfor a function with the same name as whatever the variableevaluates to, and will attempt to execute it.
function foo() {echo In foo()
\n;
}
function bar( $arg = ) {echo In bar(); argument was $arg.
\n;}
$func = foo;$func();$func = bar;$func( test );
Web Programming 2) PHP Basic Syntax
Programming in PHP: Functions 43
Error handling Exit
Terminates the execution of a program.
It does not return anything
if($thereIsAProblem){exit;
}
Die
Interrupts the execution of the program
It sends a message to the browser.
mysql query($query) or die(could not execute this query:.$query);
One can run a last function before exiting:
function err msg(){
return MySQL error was: .mysql error();}mysql query($query) or die(err msg());
Web Programming 2) PHP Basic Syntax
Programming in PHP: Functions 44
7/28/2019 Slides Beamer 2x2
12/18
OOP with PHP5
PHP5 has introduced real object oriented programming byextending the class concept of PHP4
Classes in PHP5 are not downward compatible with PHP4 PHP5 defines now the following concepts :
Classes, attributes and operations Per-class constants Class method invocation Inheritance Access modifier Static methods Object cloning Abstract classes
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 45
A simple class
class p {function p() {
print Parents c onstructor\n;}function p test() {
print p test()\n;$this>c test();
}}class c extends p {
function c() {print Childs constructor\n;parent::p();
}function c test() {
print c test()\n;}
}$obj = new c;$obj>p test();
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 46
The keyword $this Normally, one can access to an attribute or a method of a
class using the following notation :
$objectName>attribute;
or
$objectName>aMethod();
If, from within an object, one need to access to an attribute ofthe current object, the object name should be replaced by thekeyword $this as in the following examples :
$this>attribute;
or
$this>aMethod();
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 47
Instantiating a new object
A class should be considered as a general pattern to dosomething.
Once the class has been declared, it is necessary to create aninstance of this class to be able to use it.
Creating a class is done using the PHP reserved keyword new.For example :
class aClassName {private $attribute;public getAttribute () { return $this>attribute; }
}$anObject = new aClassName;
An object created this way is not initialized, i.e. noexpectation could be made on the content of $attribute
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 48
7/28/2019 Slides Beamer 2x2
13/18
Access modifiers
PHP5 has introduced 3 access modifiers to control the visibility ofthe attributes and methods. These modifiers are :
public, which mean that an attribute or a method declaredas public may be accessed from inside and outside of theclass. For compatibility reason with the earlier version of PHP,this modifier is the default if none is specified.
private, which mean that this entity may only be accessedfrom inside the class. All attributes and methods whose areonly used within the class should be declared private
protected, which mean that the entity may only be accessedfrom within the class and also from any subclass of thecurrent class.
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 49
Access modifiers (Example)These modifiers are declared in front of the attributes or methodsname. For example :
class ClassName{private $attribute;public function getAttribute() {
return $this>attribute;}public function setAttribute ($value){
$this>attribute = $value;}
}$g=new ClassName();$g>setAttribute(10);echo $g>getAttribute();
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 50
Classes constructors
If one need to ensure that the attributes of an object areproperly initialized, it is necessary to provide a special methodwhich would be automatically called every time a newinstance of the class is created.
This special method is called a constructor
In PHP5, the constructor of a class has the special name__construct()
If needed, this constructor may take some parameters
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 51
Classes constructors (Example)
A class with a constructor may look like :
class aClassName{private $attribute;function construct ($param) {
$this>attribute = $param;}
function getAttribute(){return $this>attribute;
}}$a = new aClassName(value1);$b = new aClassName(value2);
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 52
7/28/2019 Slides Beamer 2x2
14/18
Classes destructors
Normally, all attributes and variables created by a PHPprogram are automatically destroyed at the end of the script.
Sometimes it is necessary to release resources or free memory.
In this case, PHP5 introduced the notion of destructor, whichis a special method which is automatically called when anobject is destroyed.
Similarly to the constructor method, a destructor is a methodwith the special name __destruct()
Destructor cannot take parameters
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 53
Universal accessors
Generally, it is not a good idea to access directly attributesfrom outside the class. This violates the principle ofencapsulation of the data.
Therefore, attributes should normally be declared as private,
and only accessed via a method (an accessor), which will forexample ensure the consistence of datas.
PHP5 provides a way to check the access to all attributeswithin two simple methods. These are the universal accessors.
These two method have the special name __get() and__set()
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 54
Universal accessors (Example)A class using these two methods may be :
class aClassName{
private $attribute;
function get ($name) { return $this>$name; }
function set ($name, $value) {if ($name == attribute && $value >= 0 && $value $name = $value;else
echo value out of range...;}
}
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 55
Implementing Inheritance Class hierarchy and inheritance are the center concepts of
OO-programming
If a class B is a specialization of a previously defined class A, the class Bmay inherit of the class A. Sometimes it said the the class B extends theclass A.
PHP allows inheritance of classes with the reserved keyword extends. Forexample :
class A {
public $attribute1;public operation1() { ... }}
class B extends A
{public $attribute2;public operation2() { ... }
}
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 56
7/28/2019 Slides Beamer 2x2
15/18
Implementing Inheritance(Cont.)
Because the class B extends the class A, an instance of B hasaccess to all the private and protected members of A. The
following statements are all legal ;
$b = new B();$b>operation2();$b>attribute2 = 10;$b>operation1();$b>attribute1=27;
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 57
Implementing Inheritance(contd)
Very important principle of OO design:
Do not use class inheritance whenclass composition is needed !
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 58
Method overriding
We saw an example where a subclass declare new attributes ormethods
Sometimes it is useful to redeclare in a subclass a methodalready defined in a parent class to give a different meaning tothis method, in order to adapt it to the semantic of thecurrent class.
This operation is called overriding. It is possible to prevent a given method to be overridden,
using the reserved word final in front of the functiondeclaration. In that case, if someone attempt to override thismethod, PHP complain with an error message like :
Fatal error : Cannot override final method A::operation()
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 59
Per-Class class constants
PHP5 introduce the idea of a per-class constant, i.e. aconstant defined within a class, but which can be accessedwithout the need to instantiate the class.
These per-class constants are attributes declared with themodifier const. For example :
class Math
{const PI = 3.14159;
}
echo value of PI : . Math::PI . \n;
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 60
7/28/2019 Slides Beamer 2x2
16/18
Static Methods
PHP5 introduce also the static keyword. Applied tomethods, this keyword would allow these methods to be calledwithout instantiating the class. For example :
class Math{
static function squared ($input) {return $input $input;
}}
echo Math::squared(8);
The keyword $this is not allowed within static methods.
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 61
Cloning objects With PHP5, one can find a mechanism to clone objects, i.e.
to make an exact copy of an object.
To achieve that goal, PHP5 introduced a new keyword :clone.
To clone an object, one has simply to call :
$b = clone $a
Associated with the standard mechanism of cloning, PHP5defines also a new special method clone(). This methodcan be redefined if one need a special behavior for the cloningof a particular class.
The clone() method should not b e called explicitly, butwould be automatically called by the system every time thecloning mechanism is used.
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 62
Interfaces and abstract classes PHP5 introduced the concept of abstract class and interface. A class is said abstract if it provide at least one abstract
method, that is, a method which provides signature, but noimplementation.
An interface is a kind of class where all method are abstract.Since PHP5 does not support multiple inheritance, interfacesmay be used to achieve this.
An example of abstract class may be :
abstract class A{
abstract function operationX ($param1, $param2);}
Each subclass of the class A should either provide a concreteimplementation of the abstract method or be declaredabstract.
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 63
Interfaces and abstract classes An example of an interface may be :
interface B{
function display();}
A concrete class should then provide a concreteimplementation of the methods whose signature is defined inthe interface. This mechanism is called implementation of theinterface. For example :
class A implements B{
function display() { .... }}
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 64
7/28/2019 Slides Beamer 2x2
17/18
Checking the class of an object With the object oriented mechanism of PHP5, it is now possible to check
the type of an object.
This check is done at the runtime using the reserved keywordinstanceof.
If we have a class A with a subclass B, and an object $b, instance of B, wecan write :
($b instanceof B) > true($b instanceof A) > true
Another very interesting feature of PHP5 it the type hinting. Whendefining a function, it is now possible to to give a hint on the type of theaccepted parameters. For example :
function operation3(B $someclass) { ... }
Now, if one call the function with a parameter which does not answertrue to instanceof B, one will get an error of the system.
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 65
Exception handling concepts
The basic idea of exception handling is that a piece of code isexecuted within a block, called a try block
If something goes wrong within this try-block, you can throwan exception, that is, notify the remaining code of the blockthat an error was encountered.
In PHP, all exception should be manually thrown (a smalldifference with the Java environment )
Once an exception has been raised, the program jumps to theend of the try block, to another block called catch block.
In that block, the exceptions should be caught and processed.
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 66
Exception handling concepts(contd)
Example of code :
try {if ($a == 32) {
throw new Exception (A terrible error has occured, 42);}
} catch (Exception $e) {echo Exception . $e>getCode() . :
. $e>getMessage(). in . $e>getFile() . on line .
$e>getLine() .
;
}
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 67
The Exception class
class Exception {protected $message = Unknown exception; // exception messageprotected $code = 0; // user defined exception codeprotected $file; // source filename of exceptionprotected $line; // source line of exception
function construct(string $message=NULL, int code=0);
final function getMessage(); // message of exception
final function getCode(); // code of exceptionfinal function getFile(); // source filenamefinal function getTrace(); // an array of the backtrace()final function getTraceAsString(); // formated string of trace
/ Overrideable/function toString(); // formated string for display
}
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 68
7/28/2019 Slides Beamer 2x2
18/18
User-defined exceptions
A user may defines his own exception, extending the baseException class.
Defining a subclass of the Exception class may be useful to
create a more specific semantic for a given exceptionalcondition.
Since one may only override the toString() method of thebase Exception class, user-defined exception are relativelysimple to implement.
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 69
User-defined exceptionsclass MyException extends Exception {
/ Redefine the exception so message isnt optional /public function construct($message, $code = 0) {
// custom stuff you want to do..// .../ make sure everything is assigned properly /
parent:: construct($message, $code);}
/ custom string representation of object/public function toString() {
return CLASS . : [{$this>code}]: {$this>message}\n;}
public function customFunction() {echo A Custom function for this type of exception\n;
}
} Web Programming 2) PHP Basic SyntaxProgramming in PHP: Object Oriented Programming 70
Conclusion
PHP is loosely typed
The variable doent have any type The value has a type Explicite and implicite casting occures continuousely
Object Oriented Programming is new in PHP
PHP4 had a partial OO support (no encapsulation,
arguments of function were pased as value instead as referencein PHP4
Support is not trivial
Classes are loaded and interpreted on the fly. Syntax is nearing the C++ / Java syntax. Lots of libraries are not OO.
Web Programming 2) PHP Basic Syntax
Programming in PHP: Object Oriented Programming 71
Top Related