Alternatively, use : after else and use a final endif. Blocks of statements are grouped by { } Sys.Prog & Scripting - HW Univ 2

Similar documents
PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

Remember our last lecture?

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

School of Information and Computer Technology Sirindhorn International Institute of Technology Thammasat University

Client-Side Web Technologies. JavaScript Part I

AN OVERVIEW OF C++ 1

Introduction to Programming Using Java (98-388)

Polymorphism Part 1 1

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Introduce C# as Object Oriented programming language. Explain, tokens,

Quick Introduction to PHP

PHP. Interactive Web Systems

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

G52CPP C++ Programming Lecture 9

Programming for the Web with PHP

CS201- Introduction to Programming Current Quizzes

Absolute C++ Walter Savitch

JavaScript CS 4640 Programming Languages for Web Applications

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Scala : an LLVM-targeted Scala compiler

Short Notes of CS201

Functional Programming. Pure Functional Programming

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

Chapter 2: Functions and Control Structures

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CS201 - Introduction to Programming Glossary By

Problem Solving with C++

About this exam review

Princeton University COS 333: Advanced Programming Techniques A Subset of PHP

CE221 Programming in C++ Part 1 Introduction

COMP284 Scripting Languages Lecture 13: PHP (Part 5) Handouts

COMS 3101 Programming Languages: Perl. Lecture 5

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

What is PHP? [1] Figure 1 [1]

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

PHY4321 Summary Notes

PHPoC vs PHP > Overview. Overview

CERTIFICATE IN WEB PROGRAMMING

JavaScript: Sort of a Big Deal,

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

Compiler construction 2009

CSC Web Programming. Introduction to JavaScript

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

WINTER. Web Development. Template. PHP Variables and Constants. Lecture

PHPoC. PHPoC vs PHP. Version 1.1. Sollae Systems Co., Ttd. PHPoC Forum: Homepage:

Working with Functions and Classes

More on control structures

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

PHP Functions and Arrays. Orlando PHP Meetup Zend Certification Training March 2009

STRUCTURING OF PROGRAM

B. V. Patel Institute of BMC & IT 2014

CS 231 Data Structures and Algorithms, Fall 2016

CS201 Some Important Definitions

Lecture 13: more class, C++ memory management

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Exception Handling in C++

Introduction to Python (All the Basic Stuff)

Object-Oriented Programming

CS304 Object Oriented Programming Final Term

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

CPSC 427: Object-Oriented Programming

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

Object Oriented Software Design II

PHP Reference. To access MySQL manually, run the following command on the machine, called Sources, where MySQL and PhP have been installed:

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

CMSC 330: Organization of Programming Languages

Implementing Subprograms

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

Computer Science 306 Study Guide

Get Unique study materials from

Model Viva Questions for Programming in C lab

Language Features. 1. The primitive types int, double, and boolean are part of the AP

C++ (Non for C Programmer) (BT307) 40 Hours

Computer Science II (20082) Week 1: Review and Inheritance

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

PHP INTERVIEW QUESTION-ANSWERS

JavaScript CS 4640 Programming Languages for Web Applications

CMSC 202 Final May 19, Name: UserID: (Circle your section) Section: 101 Tuesday 11: Thursday 11:30

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Shell CSCE 314 TAMU. Haskell Functions

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

OO and Ahh! An Introduction to Object Oriented Programming With PHP. Division 1 Systems. John Valance. Copyright John Valance Division 1 Systems

Object-Oriented Programming in C# (VS 2015)

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Java: introduction to object-oriented features

In addition to the primary macro syntax, the system also supports several special macro types:

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

CSCE 206: Structured Programming in C++

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

The action of the program depends on the input We can create this program using an if statement

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

C++ Modern and Lucid C++ for Professional Programmers

COM S 213 PRELIM EXAMINATION #2 April 26, 2001

Transcription:

Systems Programming & Scripting Lecture 18: Control Structures Sys.Prog & Scripting - HW Univ 1 Example: If <?php if($x > $y){ echo x is greater than y ; else if($x < $y) { echo x is less than y ; else{ echo x is equal to y ;?> Sys.Prog & Scripting - HW Univ 3 PHP Control Structures If s: if (expression) else Blocks of s are grouped by { Alternatively, use : after else and use a final endif The latter is useful for mixing PHP code with HTML data Sys.Prog & Scripting - HW Univ 2 Example: If <?php if($x > $y) : echo "x is greater than y"; else : if ($x < $y) : echo "x is less than y"; else : echo "x is equal to y"; endif; endif;?> Sys.Prog & Scripting - HW Univ 4

Switch Statement switch (expression) { case value: break; default: break Sys.Prog & Scripting - HW Univ 5 Example: sum-over-array $arr = array(1,2,3,4,5); $s = 0; $i = 0; while ($i < count($arr)) { $s += $arr[$i]; $i++; echo "<p>sum over array 1..5: $s"; $x = array_sum($arr); if ($x==$s) { echo "<p>the result is correct"; else { echo "<p>the result is wrong"; Sys.Prog & Scripting - HW Univ 7 While Loop while (expression) Or while (expression) : endwhile; break and continue work as usual Sys.Prog & Scripting - HW Univ 6 do/while loop do while (expression) The loop is executed at least once Sys.Prog & Scripting - HW Univ 8

For loop for (start; condition; increment) start, condition, increment can be arbitrary expressions Semantics is the same as in C# Alternative syntax with : and endfor can be used Sys.Prog & Scripting - HW Univ 9 Example: sum-over-array $arr = array(1,2,3,4,5); $s = 0; for ($i = 0; $i < count($arr); $i++) $s += $arr[$i]; echo "<p>sum over array 1..5: $s"; Sys.Prog & Scripting - HW Univ 11 Foreach loop foreach ($array as $value) is executed for each value in $array in turn being assigned to $value foreach ($array as $key => $value) is executed for each $key to $value mapping. Sys.Prog & Scripting - HW Univ 10 Iterator functions Iterator functions generalise loops over arrays: current() returns the current array element key() returns the key of the current element reset()/end() moves the iterator to the start/end of the array next()/prev() moves the iterator to the next/previous element each() return the next key-value pair in the array Sys.Prog & Scripting - HW Univ 12

Example: sum-over-array $arr = array(1,2,3,4,5); $s = 0; while (list($key, $value) = each($arr)) $s += $value; Sys.Prog & Scripting - HW Univ 13 Serialisation PHP provides functions to serialise() and unserialise() arbitrary PHP datatypes. This can be used to store data-structures in a file, or to transfer them between machines. To unserialise, a definition of the class must be available. Sys.Prog & Scripting - HW Univ 15 Iterators over classes Iterators can also be used over arbitrary classes. Iteration is over all properties of the class. Eg. the following code, prints the values of all properties in a newly allocated cart: $cart = new Cart(); foreach($cart as $key => $value) { print "$key => $value\n"; Sys.Prog & Scripting - HW Univ 14 for/foreach Foreach is a convenient control structure to iterate through the items of an array. <?php $fruits = array ( apple => My favourite, banana => don t like, pineapple => can eat ); foreach ($fruits as $key => $value) { echo "Key: $key; Value: $value<br />\ n";?> Sys.Prog & Scripting - HW Univ 16

Useful Operations on arrays Extracting elements from an array: list($x,$y,$z) = $array; Extracting a slice from an array: $slice=array_slice($arr,$offset,$length); Splitting an array into fixed size chunks: $chunks=array_chunk($arr, $size); Extracting only keys/values: array_keys($arr); array_values($arr); Checking whether an element exists: array key exists($key, $arr); Sys.Prog & Scripting - HW Univ 17 Higher-order array functions array_walk($arr, $fct); Applies the function $fct to every array element. array_reduce($arr, $fct, $default); Combines all elements in $arr, from left to right, by applying $fct, using the value $default for the empty array. usort($arr, $fct); Sort $arr by a user-supplied $fct. Sys.Prog & Scripting - HW Univ 19 Converting between Arrays and Variables $person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty'); extract($person) generates (local) variables from the keys of this array,ie: $name = 'Fred'; $age = 35; $wife = 'Betty'; compact('name', 'age', 'wife') does the opposite Sys.Prog & Scripting - HW Univ 18 More array functions PHP provides families of functions to treat arrays as Sets Stacks For finding an element in an array: in_array($elem, $arr); Sys.Prog & Scripting - HW Univ 20

Including code include file_name Or require file_name Loads the code in file_name; for require the file must exist Warnings from loading the code are supressed, if @include is used If permitted by the php.ini configuration file, code can be loaded from (remote) URLs Sys.Prog & Scripting - HW Univ 21 Functions Functions abstract over and parameterise code. They are like C# methods. As usual, you have to define: The function name The names of the arguments NOT: the types of parameters and result Sys.Prog & Scripting - HW Univ 23 Example: header and footer The following code reads functions, generating a footer and a header for the web page from the library design.inc <?php require 'design.inc'; header();?> content <?php footer();?> Sys.Prog & Scripting - HW Univ 22 Function Definitions function [&] function_name ([ [&]param [, ]]) Only names but not types have to be specified. A function has 0 or more parameters; param: arguments are passed by value &param: arguments are passed by reference The body of the code can include HTML text An optional & indicates that a reference to data, rather than the data itself, is returned Sys.Prog & Scripting - HW Univ 24

Example: String concatenation function strcat ($left, $right) { $combined = $left. $right; return $combined; echo strcat("<p>", strcat("hello ", "World")); Sys.Prog & Scripting - HW Univ 25 More on Parameter Passing Specifying default parameters: function get_preferences($what = all ){... If no argument is provided when calling the function, $what takes the value all Variable number of parameters: function get_preferences () And use these functions in the body: $arr = func_get_args(); $count = func_num_args(); $value = func get arg(arg number); Sys.Prog & Scripting - HW Univ 27 Scope of Variables Variables in functions are local, i.e. different from variables with the same name defined outside the function. The keyword global is used to access the variables in the outer scope The keyword static is used to create a variable that remembers its value after leaving the function Sys.Prog & Scripting - HW Univ 26 Anonymous functions To define a nameless function use: create_function(args_string,code_string); This function can be passed as argument to other functions It is possible to use function variables: $myfun(); First evaluates the variable $myfun, which must be a function, and then calls it Sys.Prog & Scripting - HW Univ 28

Example: Customised sorting // create an anonymous function $lambda = create_function('$a,$b', 'return(strlen($a)-strlen($b));'); // array to be sorted $arr = array('some string', 'yet another string', 'a string'); // sort array by str-length usort($arr, $lambda); // print it print_r($arr); Sys.Prog & Scripting - HW Univ 29 Class Declaration class class_name [extends base_class] { [ var $property [ = value]; ] [ [static] function fct (args) { ] A class can inherit properties and methods from a base_class Properties may be initialised Methods can be static, ie once per-class Or refer to the object as $this Sys.Prog & Scripting - HW Univ 31 Objects PHP is a full-blown object-oriented language The syntax for defining classes, classhierarchies and object is similar to C# A class contains Properties (data) Methods (code) The new construct creates an object Infix is used to refer to a property/method Sys.Prog & Scripting - HW Univ 30 The usual stuff Access modifiers public, protected, private can be used to control access to properties Properties can be static, ie once per class To refer to a static property/method write: class_name::property/method must be used To access a property/method from the parent class: parent::property/method Constants can be declared like this: const name = value; Sys.Prog & Scripting - HW Univ 32

Interfaces interface interface_name { [ function function_name (); ] Defines the functions that should be supplied through the interface. The keyword implements is used on class declaration Sys.Prog & Scripting - HW Univ 33 Constructors/Destructors The constructor of a class must have the name constructor It is executed whenever new is called on the class The destructor of a class must have the name destructor It is executed automatically when an object is not used any more PHP performs automatic garbage collection Sys.Prog & Scripting - HW Univ 35 Abstract Classes/Methods abstract class class_name { [ abstract function function_name (); ] To collect methods, common to several classes, abstract classes with abstract methods are used. Concrete classes inherit from them as usual Sys.Prog & Scripting - HW Univ 34 Example: Shopping Cart // interface for a general collection interface MyCollection { function add_item($art_nr, $num); function remove_item($artnr, $num); function show (); Sys.Prog & Scripting - HW Univ 36

Example: Shopping Cart class Cart implements MyCollection { var $items; var $debug = true; function add_item($art_nr, $num) { $this->items[$art_nr] += $num; function show () { echo "<table>\n"; echo "<td>item</td><td>quantity</td><tr>\n"; foreach ($this->items as $key => $value) { echo "<td> $key</td> <td> $value </td> <tr>\ n"; echo "</table>\n"; Sys.Prog & Scripting - HW Univ 37 Example: Shopping Cart $another_cart = new Cart(); $another_cart->add_item("0815", 3); $another_cart->add_item("13", 1); $another_cart->add_item("99", 9); if ($another_cart!= null) { echo "You have a second cart, with this contents:<br>"; $another_cart->show(); $another_cart->remove_item("99", 8); $another_cart->remove_item("0815", 3); $another_cart->remove_item("55", 1); if ($another_cart!= null) { echo "After removing some items the contents is:<br>"; $another_cart->show(); Sys.Prog & Scripting - HW Univ 39 Example: Shopping Cart function remove_item($artnr, $num) { if (!array_key_exists($artnr, $this->items)) { if ($this->debug) { echo "<P>Warning: Trying to remove non existing item $artnr<br>\n"; return false; if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; else if ($this->items[$artnr] == $num) { unset($this->items[$artnr]); // remove entry return true; else { return false; Sys.Prog & Scripting - HW Univ 38 Exceptions PHP provides exceptions very similar to those in C#, eg. function inverse($x) { if (!$x) { throw new Exception('Division by zero.'); else return 1/$x; try { echo inverse(5). "\n"; echo inverse(0). "\n"; catch (Exception $e) { echo 'Caught exception: ', $e->getmessage(); Sys.Prog & Scripting - HW Univ 40

Exceptions Try-catch blocks can be nested. Several catch-branches may be attached to a try, covering different exceptions. Tailored exceptions are defined by extending the pre-defined Exception class: class MyException extends Exception { Sys.Prog & Scripting - HW Univ 41 Namespaces PHP 5.3 onwards provides the concept of namespaces, to avoid name-clashes between modules. The definition of a namespace must be at the start of the file, eg. namespace ThisModule { Namespaces can be nested, eg. namespace ThisModule\SubModule { To refer to an object, use the notation SubModule\SomeClass::SomeMethod() Or a fully qualified name \ThisModule\SubModule\SomeClass::SomeMethod() Sys.Prog & Scripting - HW Univ 43 Type Hinting PHP can provide hints on type information. For example arguments to functions may be restricted to certain classes, or to be of an array type. This recovers some of the safety from statically typed languages. public function test(otherclass $otherclass) { echo $otherclass->var; Sys.Prog & Scripting - HW Univ 42 New Features in PHP 5.4 Traits: are a simple extension to class hierarchies, that allows to mix code between classes (similar to mixins) act like syntactic inclusion of code have no runtime overhead can be composed but: onflicts have to be resolved explicitly See: https://wiki.php.net/rfc/horizontalreuse Short-hand syntax to array initialisation Stand-alone PHP web server Sys.Prog & Scripting - HW Univ 44

Traits in PHP 5.4 class Base { public function sayhello() { echo 'Hello '; trait SayWorld { public function sayhello() { parent::sayhello(); echo 'World!'; class MyHelloWorld extends Base { use SayWorld; $o = new MyHelloWorld(); $o->sayhello(); // echos Hello World! Sys.Prog & Scripting - HW Univ 45 Exercise Implement the sum-over-array example using iterator constructs. Extend the shopping cart example to additionally store with each article a unit price and a currency. Compute the total costs of all articles in the shopping cart. Implement a function that converts all prices from one currency to another (GBP, EUR, USD). Write a PHP script, that reads a data file from the Big MACS store manager of coursework 1, and display the contents of the file in table. The supplier should be highlighted. The user should be able to pick the filename via a form. Sys.Prog & Scripting - HW Univ 46