Sie sind auf Seite 1von 85

Web Programming

2) PHP Basic Syntax


Emmanuel Benoist
Fall Term 2013-14

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 1
Introduction

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 2
What is PHP ?

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 3
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.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 4
Basic concepts of PHP
 Introduction
What is PHP ?
Starting with PHP
 Basic Syntax
Numbers
Strings
Arrays
Variables
Constants
Control Structures
Include files
 Programming in PHP
Functions
Object Oriented Programming

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 5
Starting with PHP

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 6
Our First PHP File:

A php file is an HTML file containing PHP instructions.

<html> <body>
<? echo (this is the simplest, an SGML processing instruction&
\n); ?>

<br>
<?php echo(if you want to serve XML documents, do like &
this\n); ?>

</body>
</html>

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 7
Instruction separation

Generally an instruction terminate with a ; but the


closing tag also implies the end of the statement

<?php echo This is a test;


?>

<?php echo This is a second test?>

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 8
Comments
PHP supports C, C++ (=Java) and Unix shell style
comments
<?php
echo Hello World ;); // This is a comment
/ This is an other comment
You can write on multiple lines /

echo Welcome on my home page; # a shellstyle comment


?>

The one-line comment


The one-line comment styles actually only comment to the
end of the line or the current block of PHP code, whichever
comes first.
<h1>This is an <?php # echo simple;?> example.</h1>
<p>The header above will say This is an example.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 9
Comments (Cont.)

You should be careful not to nest C style comments,


<?php
/
echo This is a test;
/ This comment will cause a problem /
function calcul(){
DoSomething();
}
/
?>

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 10
Basic Syntax

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 11
Numbers

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 12
Numbers

Integers
$a = 1234; # decimal number
$a = 123; # a negative number
$a = 0123; # octal number (equivalent to 83 decimal)
$a = 0x12; # hexadecimal number (equivalent to 18 &
decimal)

Floating point numbers


$a = 1.234;
$a = 1.2e3;

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 13
Strings

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 14
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 and
Perl, 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

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 15
Other string examples
$name=Emmanuel;
$str1 = Hello $name;
$str2 = Hello $name;
echo $str1; // The name is replaced
echo $str2; // $name appears on the screen
echo <br>\n;
$str3 = hello \n;
$str4 = world <br>\n;
echo $str3;
echo $str4;
echo $str3.$str4;
Output (in the browser)
Hello EmmanuelHello $name
hello world
hello world
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 16
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 character
in octal notation
\x[0 9A Fa f ]{1, 2} the sequence of characters matching
the regular expression is a character
in hexadecimal notation

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 17
Here doc
here doc syntax (<<<)
One provides an identifier after <<<, then the string, and then the
same identifier to close the quotation.
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/ More complex example, with variables. /
class foo {
var $foo;
var $bar;
function foo() {
$this>foo = Foo;
$this>bar = array(Bar1, Bar2, Bar3);
}
}
$foo = new foo();
$name = MyName;
echo <<<EOT
My name is $name. I am printing some $foo>foo.
Now, I am printing some {$foo>bar[1]}.
This should print a capital A: \x41
EOT;

Here doc text behaves just like a double-quoted string, without the
double-quotes.
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 18
More with Strings
Strings may be concatenated using the . (dot) operator. Note
that the + (addition) operator will not work for this.
Characters within strings may be accessed by treating the string as
a 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 <p>Number: 9</p> /
$num = 9;
$str = <p>Number: $num</p>;
/ This one will be <p>Number: $num</p> /
$num = 9;
$str = <p>Number: $num</p>;
/ 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];

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 19
String conversion
When a string is evaluated as a numeric value, the
resulting value and type are determined as follows.
The string will evaluate as a double if it contains any of the
characters ., e, or E. Otherwise, it will evaluate as an
integer.
The value is given by the initial portion of the string. If the
string starts with valid numeric data, this will be the value
used. Otherwise, the value will be 0 (zero).
Valid numeric data is an optional sign, followed by one or more
digits (optionally containing a decimal point), followed by an
optional 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 variable
will depend on the second expression.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 20
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)

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 21
Arrays

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 22
Single Dimension Arrays
PHP does not make a great difference between arrays (indexed
with 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

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 23
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!

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 24
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
);

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 25
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

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 26
Variables

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 27
Type Juggling
PHP does not require (or support) explicit type
definition in variable declaration;
A variables type is determined by the context in which that
variable 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)

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 28
Type casting

To change the type of an element you have to give the


desired 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

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 29
Variables : Basics
Variables in PHP are represented by a dollar sign
followed by the name of the variable. The variable name
is 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
$t
ayte = mansikka; // valid; 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;

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 30
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.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 31
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

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 32
Variables (Cont.)
Static variables
The value of a static variable exists only in a local function scope, but
remains the same for many execution

// Useless Function it does nothing


function Test3(){
$a = 0;
echo $a;
$a++;
}
// This function allows us to increment a counter
function Test4(){
static $a = 0;
echo $a;
$a++;
}
Test3();Test3();Test3();
echo ;;
Test4();Test4();Test4();

Output : 000;012

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 33
Variable variables
Sometimes 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 the
name of a variable.
In the above example, hello, can be used as the name of a variable by
using two dollar signs. i.e.
$$a = world;
At this point two variables have been defined and stored in the PHP
symbol 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

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 34
Constants

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 35
Constants

There exists predefine constants, such as TRUE, FALSE,


PHP VERSION or PHP OS.
Moreover can you define your own constants using the
define() function.
<?php
define(CONSTANT, Hello world.);
echo CONSTANT; // outputs Hello world.
?>

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 36
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.

<?php
function report error($file, $line, $message) {
echo An error occured in $file on line $line: $message.&
;

}
report error( FILE , LINE , Something went wrong!);
?>

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 37
Control Structures

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 38
Control Structures : IF
C like IF
if($a>$b){ echo $a is strictly greater that $b <br>\n;
}
elseif($a==$b){ echo $a is equal to $b <br>\n;
}
else{ echo $a is strictly smaller that $b <br>\n;
}

Output : 12 is strictly smaller that 13


Embaded in HTML code
<?php if($a>$b): ?> a is strictly greater that b <br>
<?php elseif ($a==$b): ?> a is equal to b <br>
<?php else: ?> a is strictly smaller that b <br>
<?php endif; ?>

Output : a is strictly smaller that b

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 39
Control Structures : WHILE
C like
$i=1;
while ($i<100){
$i=2;
}
echo i = $i<br>\n;
Output : i = 128
Embeded Syntax
$j=1;
while ($j<100):
$j=2;
endwhile;
echo j = $j<br>\n;
Output : j = 128

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 40
Control Structures : DO..WHILE

Only one syntax


$i = 0;
do{
print $i;
}while ($i>0);

echo <br>\n;
Output : 0

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 41
Control Structures : FOR

# C like code
for ($i=0; $i <=10; $i++){
print $i;
}
# PHP like code
for($i=0; $i <=10; $i++):
print $i;
endfor;

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 42
Foreach
PHP includes a foreach construct, much like Java 1.5 and some
other languages. This simply gives an easy way to iterate over
arrays.
foreach(array expression as $value) statement
foreach(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 (so
on the next loop, youll be looking at the next element).
The second form does the same thing, except that the current
elements key will be assigned to the variable $key on each
loop.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 43
Foreach (Cont.)

Visit all the values of an Array


foreach ($arr as $value) {
echo Value: $value<br>\n;
}
Visit the values and the keys
foreach ($arr as $key => $value) {
echo Key: $key; Value: $value<br>\n;
}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 44
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;
}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 45
Break
break ends execution of the current for, while, or switch structure.
break accepts an optional numeric argument which tells it how many nested
enclosing 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<br>\n;
}

/ Using the optional argument. /


$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo At 5<br>\n;
break 1; / Exit only the switch. /
case 10:
echo At 10; quitting<br>\n;
break 2; / Exit the switch and the while. /
default:
break;
}
}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 46
Continue
continue is used within looping structures to skip the
rest of the current loop iteration and continue execution
at the beginning of the next iteration.
while (list ($key, $value) = each ($arr)) {
if (!($key % 2)) { // skip odd members
continue;
}
do something odd ($value);
}
$i = 0;
while ($i++ < 5) {
echo Outer<br>\n;
while (1) {
echo Middle<br>\n;
while (1) {
echo Inner<br>\n;
continue 3;
}
echo This never gets output.<br>\n;
}
echo Neither does this.<br>\n;
}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 47
Switch
The switch statement is similar to a series of IF statements on the
same 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;
}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 48
Include files

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 49
require()
The require() statement replaces itself with the
specified file, much like the C preprocessors #include
works.
require() and require once() produce a fault when the
resource 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 the


specified file.
Almost the same without creating an error.
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 50
Programming in PHP

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 51
Functions

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 52
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];
}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 53
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, you
must pass them by reference.
If you want an argument to a function to always be passed by
reference, you can prepend an ampersand (&) to the
argument 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.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 54
User defined functions(Cont.)
If you wish to pass a variable by reference to a function which does
not do this by default, you may prepend an ampersand to the
argument 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.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 55
Variable functions
PHP supports the concept of variable functions. This means that
if a variable name has parentheses appended to it, PHP will look
for a function with the same name as whatever the variable
evaluates to, and will attempt to execute it.
function foo() {
echo In foo()<br>\n;
}

function bar( $arg = ) {


echo In bar(); argument was $arg.<br>\n;
}

$func = foo;
$func();
$func = bar;
$func( test );

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 56
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());

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 57
Object Oriented Programming

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 58
OOP with PHP5

PHP5 has introduced real object oriented programming by


extending 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

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 59
A simple class
class p {
function p() {
print Parents constructor\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();

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 60
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 of


the current object, the object name should be replaced by the
keyword $this as in the following examples :
$this>attribute;
or
$this>aMethod();

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 61
Instantiating a new object
A class should be considered as a general pattern to do
something.
Once the class has been declared, it is necessary to create an
instance 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. no


expectation could be made on the content of $attribute

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 62
Access modifiers
PHP5 has introduced 3 access modifiers to control the visibility of
the attributes and methods. These modifiers are :
public, which mean that an attribute or a method declared
as public may be accessed from inside and outside of the
class. 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 accessed
from inside the class. All attributes and methods whose are
only used within the class should be declared private
protected, which mean that the entity may only be accessed
from within the class and also from any subclass of the
current class.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 63
Access modifiers (Example)
These modifiers are declared in front of the attributes or methods
name. 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();

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 64
Classes constructors

If one need to ensure that the attributes of an object are


properly initialized, it is necessary to provide a special method
which would be automatically called every time a new
instance 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

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 65
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);

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 66
Classes destructors

Normally, all attributes and variables created by a PHP


program 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, which
is a special method which is automatically called when an
object is destroyed.
Similarly to the constructor method, a destructor is a method
with the special name __destruct()
Destructor cannot take parameters

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 67
Universal accessors

Generally, it is not a good idea to access directly attributes


from outside the class. This violates the principle of
encapsulation of the data.
Therefore, attributes should normally be declared as private,
and only accessed via a method (an accessor), which will for
example ensure the consistence of datas.
PHP5 provides a way to check the access to all attributes
within two simple methods. These are the universal accessors.
These two method have the special name __get() and
__set()

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 68
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 <= &

100)

$this>$name = $value;
else
echo value out of range...;
}
}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 69
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 B
may inherit of the class A. Sometimes it said the the class B extends the
class A.
PHP allows inheritance of classes with the reserved keyword extends. For
example :
class A {
public $attribute1;
public operation1() { ... }
}

class B extends A
{
public $attribute2;
public operation2() { ... }
}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 70
Implementing Inheritance (Cont.)

Because the class B extends the class A, an instance of B has


access 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;

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 71
Implementing Inheritance (contd)

Very important principle of OO design:

Do not use class inheritance when


class composition is needed !

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 72
Method overriding
We saw an example where a subclass declare new attributes or
methods
Sometimes it is useful to redeclare in a subclass a method
already defined in a parent class to give a different meaning to
this method, in order to adapt it to the semantic of the
current 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 function
declaration. In that case, if someone attempt to override this
method, PHP complain with an error message like :
Fatal error : Cannot override final method A::operation()

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 73
Per-Class class constants
PHP5 introduce the idea of a per-class constant, i.e. a
constant defined within a class, but which can be accessed
without the need to instantiate the class.
These per-class constants are attributes declared with the
modifier const. For example :
class Math
{
const PI = 3.14159;
}

echo value of PI : . Math::PI . \n;

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 74
Static Methods
PHP5 introduce also the static keyword. Applied to
methods, this keyword would allow these methods to be called
without 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.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 75
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, PHP5


defines also a new special method clone(). This method
can be redefined if one need a special behavior for the cloning
of a particular class.
The clone() method should not be called explicitly, but
would be automatically called by the system every time the
cloning mechanism is used.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 76
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 no
implementation.
An interface is a kind of class where all method are abstract.
Since PHP5 does not support multiple inheritance, interfaces
may 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 concrete
implementation of the abstract method or be declared
abstract.
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 77
Interfaces and abstract classes
An example of an interface may be :
interface B
{
function display();
}

A concrete class should then provide a concrete


implementation of the methods whose signature is defined in
the interface. This mechanism is called implementation of the
interface. For example :
class A implements B
{
function display() { .... }
}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 78
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 keyword
instanceof.
If we have a class A with a subclass B, and an object $b, instance of B, we
can write :
($b instanceof B) > true
($b instanceof A) > true

Another very interesting feature of PHP5 it the type hinting. When


defining a function, it is now possible to to give a hint on the type of the
accepted parameters. For example :
function operation3(B $someclass) { ... }

Now, if one call the function with a parameter which does not answer
true to instanceof B, one will get an error of the system.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 79
Exception handling concepts

The basic idea of exception handling is that a piece of code is


executed within a block, called a try block
If something goes wrong within this try-block, you can throw
an exception, that is, notify the remaining code of the block
that an error was encountered.
In PHP, all exception should be manually thrown (a small
difference with the Java environment )
Once an exception has been raised, the program jumps to the
end of the try block, to another block called catch block.
In that block, the exceptions should be caught and processed.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 80
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() . <br>;
}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 81
The Exception class
class Exception {
protected $message = Unknown exception; // exception message
protected $code = 0; // user defined exception code
protected $file; // source filename of exception
protected $line; // source line of exception

function construct(string $message=NULL, int code=0);

final function getMessage(); // message of exception


final function getCode(); // code of exception
final function getFile(); // source filename
final function getTrace(); // an array of the backtrace()
final function getTraceAsString(); // formated string of trace

/ Overrideable /
function toString(); // formated string for display
}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 82
User-defined exceptions

A user may defines his own exception, extending the base


Exception class.
Defining a subclass of the Exception class may be useful to
create a more specific semantic for a given exceptional
condition.
Since one may only override the toString() method of the
base Exception class, user-defined exception are relatively
simple to implement.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 83
User-defined exceptions
class 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;
}

}
Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 84
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 came late in PHP5
PHP4 had a partial OO support (no encapsulation)
arguments of function were pased as value instead as reference
in PHP4
Support is not trivial
Classes are loaded and interpreted on the fly.
There is no class loader, everything must be loaded.
Syntax is nearing the C++ / Java syntax.
Lots of libraries are not OO.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 85