web programming 2) php basic syntax

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

Upload: others

Post on 12-Sep-2021

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Web Programming 2) PHP Basic Syntax

Web Programming2) PHP Basic Syntax

Emmanuel BenoistFall Term 2013-14

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

Page 2: Web Programming 2) PHP Basic Syntax

Introduction

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

Page 3: Web Programming 2) PHP Basic Syntax

What is PHP ?

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

Page 4: Web Programming 2) PHP Basic Syntax

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

Page 5: Web Programming 2) PHP Basic Syntax

Basic concepts of PHP� Introduction

What is PHP ?Starting with PHP

� Basic SyntaxNumbersStringsArraysVariablesConstantsControl StructuresInclude files

� Programming in PHPFunctionsObject Oriented Programming

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

Page 6: Web Programming 2) PHP Basic Syntax

Starting with PHP

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

Page 7: Web Programming 2) PHP Basic Syntax

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

Page 8: Web Programming 2) PHP Basic Syntax

Instruction separation

Generally an instruction terminate with a “;” but theclosing 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

Page 9: Web Programming 2) PHP Basic Syntax

Comments

PHP supports C, C++ (=Java) and Unix shell stylecomments

<?phpecho ”Hello World ;−)”; // This is a comment/∗ This is an other commentYou can write on multiple lines ∗/

echo ”Welcome on my home page”; # a shell−style comment?>

The ”one-line” commentThe ”one-line” comment styles actually only comment to theend of the line or the current block of PHP code, whichevercomes 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

Page 10: Web Programming 2) PHP Basic Syntax

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

Page 11: Web Programming 2) PHP Basic Syntax

Basic Syntax

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

Page 12: Web Programming 2) PHP Basic Syntax

Numbers

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

Page 13: Web Programming 2) PHP Basic Syntax

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

Page 14: Web Programming 2) PHP Basic Syntax

Strings

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

Page 15: Web Programming 2) PHP Basic Syntax

Strings

Two sets of delimiters ’ ’ and ” ” (like in perl)

Delimiters quote ’ ’ : The text is a stringDelimiters double-quote ” ”: variables within the string will beexpanded (subject to some parsing limitations). As in C andPerl, the backslash (”\”) character can be used in specifyingspecial 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

Page 16: Web Programming 2) PHP Basic Syntax

Other string examples$name=’Emmanuel’;$str1 = ”Hello $name”;$str2 = ’Hello $name’;echo $str1; // The name is replacedecho $str2; // $name appears on the screenecho ”<br>\n”;$str3 = ”hello \n”;$str4 = ”world <br>\n”;echo $str3;echo $str4;echo $str3.$str4;

Output (in the browser)

Hello EmmanuelHello $namehello worldhello world

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

Page 17: Web Programming 2) PHP Basic Syntax

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 matchingthe 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

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

Page 18: Web Programming 2) PHP Basic Syntax

Here dochere doc syntax (”<<<”)One provides an identifier after <<<, then the string, and then thesame identifier to close the quotation.

$str = <<<EODExample of stringspanning multiple linesusing 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 <<<EOTMy name is ”$name”. I am printing some $foo−>foo.Now, I am printing some {$foo−>bar[1]}.This should print a capital ’A’: \x41EOT;

Here doc text behaves just like a double-quoted string, without thedouble-quotes.

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

Page 19: Web Programming 2) PHP Basic Syntax

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 ’<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

Page 20: Web Programming 2) PHP Basic Syntax

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.

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

Page 21: Web Programming 2) PHP Basic Syntax

String conversion(Cont.)

$foo = 1 + ”10.5”; // $foo is double (11.5)$foo = 1 + ”−1.3e3”; // $foo is double (−1299)$foo = 1 + ”bob−1.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

Page 22: Web Programming 2) PHP Basic Syntax

Arrays

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

Page 23: Web Programming 2) PHP Basic Syntax

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”

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

Page 24: Web Programming 2) PHP Basic Syntax

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

Page 25: Web Programming 2) PHP Basic Syntax

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

Page 26: Web Programming 2) PHP Basic Syntax

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” => ”paste−y”,”shape” => ”banana−shaped”));

echo $a[”apple”][”taste”]; # will output ”sweet”

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

Page 27: Web Programming 2) PHP Basic Syntax

Variables

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

Page 28: Web Programming 2) PHP Basic Syntax

Type Juggling

PHP does not require (or support) explicit typedefinition in variable declaration;

A variable’s 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)

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

Page 29: Web Programming 2) PHP Basic Syntax

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

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

Page 30: Web Programming 2) PHP Basic Syntax

Variables : Basics

Variables in PHP are represented by a dollar signfollowed 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’; // 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

Page 31: Web Programming 2) PHP Basic Syntax

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

Page 32: Web Programming 2) PHP Basic Syntax

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

Page 33: Web Programming 2) PHP Basic Syntax

Variables (Cont.)

Static variablesThe 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

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

Page 34: Web Programming 2) PHP Basic Syntax

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

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

Page 35: Web Programming 2) PHP Basic Syntax

Constants

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

Page 36: Web Programming 2) PHP Basic Syntax

Constants

There exists predefine constants, such as TRUE, FALSE,PHP VERSION or PHP OS.Moreover can you define your own constants using thedefine() function.

<?phpdefine(”CONSTANT”, ”Hello world.”);echo CONSTANT; // outputs ”Hello world.”?>

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

Page 37: Web Programming 2) PHP Basic Syntax

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.

<?phpfunction 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

Page 38: Web Programming 2) PHP Basic Syntax

Control Structures

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

Page 39: Web Programming 2) PHP Basic Syntax

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

Page 40: Web Programming 2) PHP Basic Syntax

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

Page 41: Web Programming 2) PHP Basic Syntax

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

Page 42: Web Programming 2) PHP Basic Syntax

Control Structures : FOR

# C like codefor ($i=0; $i <=10; $i++){

print $i;}# PHP like codefor($i=0; $i <=10; $i++):

print $i;endfor;

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

Page 43: Web Programming 2) PHP Basic Syntax

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, you’ll be looking at the next element).

The second form does the same thing, except that the currentelement’s key will be assigned to the variable $key on eachloop.

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

Page 44: Web Programming 2) PHP Basic Syntax

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

Page 45: Web Programming 2) PHP Basic Syntax

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

Page 46: Web Programming 2) PHP Basic Syntax

Break

break 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<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

Page 47: Web Programming 2) PHP Basic Syntax

Continuecontinue is used within looping structures to skip therest 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<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

Page 48: Web Programming 2) PHP Basic Syntax

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

}

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

Page 49: Web Programming 2) PHP Basic Syntax

Include files

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

Page 50: Web Programming 2) PHP Basic Syntax

require()

The require() statement replaces itself with thespecified file, much like the C preprocessor’s #includeworks.require() and require once() produce a fault when theresource is not available.

// imports all the functions and classesrequire (”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.

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

Page 51: Web Programming 2) PHP Basic Syntax

Programming in PHP

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

Page 52: Web Programming 2) PHP Basic Syntax

Functions

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

Page 53: Web Programming 2) PHP Basic Syntax

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

Page 54: Web Programming 2) PHP Basic Syntax

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.’

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

Page 55: Web Programming 2) PHP Basic Syntax

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.’

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

Page 56: Web Programming 2) PHP Basic Syntax

Variable functions

PHP 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()<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

Page 57: Web Programming 2) PHP Basic Syntax

Error handlingExit

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

Page 58: Web Programming 2) PHP Basic Syntax

Object Oriented Programming

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

Page 59: Web Programming 2) PHP Basic Syntax

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 operationsPer-class constantsClass method invocationInheritanceAccess modifierStatic methodsObject cloningAbstract classes

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

Page 60: Web Programming 2) PHP Basic Syntax

A simple class

class p {function p() {

print ”Parent’s constructor\n”;}function p test() {

print ”p test()\n”;$this−>c test();

}}class c extends p {

function c() {print ”Child’s 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

Page 61: Web Programming 2) PHP Basic Syntax

The keyword $this

Normally, one can access to an attribute or a method of aclass 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();

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

Page 62: Web Programming 2) PHP Basic Syntax

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

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

Page 63: Web Programming 2) PHP Basic Syntax

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.

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

Page 64: Web Programming 2) PHP Basic Syntax

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();

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

Page 65: Web Programming 2) PHP Basic Syntax

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

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

Page 66: Web Programming 2) PHP Basic Syntax

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

Page 67: Web Programming 2) PHP Basic Syntax

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

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

Page 68: Web Programming 2) PHP Basic Syntax

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()

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

Page 69: Web Programming 2) PHP Basic Syntax

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;

elseecho ”value out of range...”;

}}

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

Page 70: Web Programming 2) PHP Basic Syntax

Implementing InheritanceClass hierarchy and inheritance are the center concepts ofOO-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 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() { ... }

}

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

Page 71: Web Programming 2) PHP Basic Syntax

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. Thefollowing 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

Page 72: Web Programming 2) PHP Basic Syntax

Implementing Inheritance (cont’d)

Very important principle of OO design:

Do not use class inheritance whenclass composition is needed !

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

Page 73: Web Programming 2) PHP Basic Syntax

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()

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

Page 74: Web Programming 2) PHP Basic Syntax

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

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

Page 75: Web Programming 2) PHP Basic Syntax

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.

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

Page 76: Web Programming 2) PHP Basic Syntax

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 be called explicitly, butwould be automatically called by the system every time thecloning mechanism is used.

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

Page 77: Web Programming 2) PHP Basic Syntax

Interfaces and abstract classesPHP5 introduced the concept of abstract class and interface.

A class is said abstract if it provide at least one abstractmethod, 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.

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

Page 78: Web Programming 2) PHP Basic Syntax

Interfaces and abstract classesAn 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() { .... }}

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

Page 79: Web Programming 2) PHP Basic Syntax

Checking the class of an object

With the object oriented mechanism of PHP5, it is now possible to checkthe 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.

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

Page 80: Web Programming 2) PHP Basic Syntax

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.

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

Page 81: Web Programming 2) PHP Basic Syntax

Exception handling concepts (cont’d)

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

Page 82: Web Programming 2) PHP Basic Syntax

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 exceptionfinal 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}

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

Page 83: Web Programming 2) PHP Basic Syntax

User-defined exceptions

A user may defines his own exception, extending the baseException class.

Defining a subclass of the Exception class may be useful tocreate 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.

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

Page 84: Web Programming 2) PHP Basic Syntax

User-defined exceptionsclass MyException extends Exception {

/∗ Redefine the exception so message isn’t 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

Page 85: Web Programming 2) PHP Basic Syntax

Conclusion

PHP is loosely typedThe variable doen’t have any typeThe value has a typeExplicite and implicite casting occures continuousely

Object Oriented Programming came late in PHP5PHP4 had a partial OO support (no encapsulation)arguments of function were pased as value instead as referencein PHP4

Support is not trivialClasses 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