Intermediate PHP (2) File Input/Output & User Defined Functions.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
Outline What Is Function ? Create Function Call Function Parameters Functions Function Returning Values PHP Variable Scopes Passing by Reference Vs Value.
More on PHP Coding Lab no. 6 Advance Database Management System.
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
Introduction to C Programming
COMP An Introduction to Computer Programming : University of the West Indies COMP6015 An Introduction to Computer Programming Lecture 06.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
WEB DESIGN AND PROGRAMMING Introduction to Javascript.
Introduction to PHP (1) Background, Data Types, Control Structures & Functions.
Lesson 1: Introduction to ABAP OBJECTS Todd A. Boyle, Ph.D. St. Francis Xavier University.
Week 9 PHP Cookies and Session Introduction to JavaScript.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
2440: 211 Interactive Web Programming Expressions & Operators.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Web Programming with PHP (2). PHP Scripts o every PHP script is a collection of one or more statements; these statements appear as a collection of names,
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
Hans-Peter Plag November 6, 2014 Session 4 (Programming Languages) (Data Types and Variables) Expressions and Operators Flow Control.
C STRUCTURES. A FIRST C PROGRAM  #include  void main ( void )  { float height, width, area, wood_length ;  scanf ( "%f", &height ) ;  scanf ( "%f",
Web Database Programming Week 3 PHP (2). Functions Group related statements together to serve “a” specific purpose –Avoid duplicated code –Easy maintenance.
Chapter 2 User_defined Function. Chapter Goals In this chapter, you’ll learn all about PHP functions, including how : to create and invoke them, pass.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Storing and Retrieving Data
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
JavaScript, Fourth Edition
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
PHP Function. Outline o What Is Function ? o Create Function o Call Function o Parameters Functions o Function Returning Values o Passing by Reference.
UFCE8V-20-3 Information Systems Development 3 PHP (1) : Data Types, Control Structures, Data Structures, String Handling & Input/Output.
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
JavaScript: Functions © by Pearson Education, Inc. All Rights Reserved.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Basics.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
JavaScript: Functions
JavaScript Functions.
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
JavaScript: Functions.
PHP Introduction.
11/10/2018.
Chapter 5 - Functions Outline 5.1 Introduction
PHP.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Basics (Cont...).
Intro to PHP.
Web Programming with PHP (2)
SEEM 4540 Tutorial 4 Basic PHP based on w3Schools
Presentation transcript:

Intermediate PHP (2) File Input/Output & User Defined Functions

last week … PHP origins & use Basic Web tier/3-tier architecture with PHP PHP as a scripting language (supporting procedural & oo paradigms) Basic structure & use (statements, variables, control structures, operators) PHP data types - 5 basic – integer, floating-point, string, boolean & NULL & 3 complex - array, hash & object PHP Functions Library (700+) – string handling, input/output, date & time, db interaction, xml processing etc. etc. the exit & die() statements

File Input / Output & Disk Access (1) Reading and Writing to Files Communicating with files follows the pattern of opening a stream to a file, reading from or writing to it, and then closing the stream. fopen(..) : the fopen function opens a file for reading or writing. The function expects the name of a file and a mode e.g. fopen (‘c:/temp/myfile.txt’, ‘r’); which opens a file called ‘myfile.txt’ in the directory ‘c:/temp’ in the “read” mode File read/write modes : rreading only wwrite only, create if necessary, discard previous content aappend to file, create if necessary, start writing at end r+reading and writing w+reading & writing, create if necessary, discard previous content a+reading & writing, create if necessary, start writing at end

Input / Output & Disk Access (2) fclose (resource file) : used to close a file. feof (resource file) : as a file is read, php keeps a pointer to the last place in the file read; the feof function returns true if the end of file is reached. fgetcsv(resource file, integer length, string separator) : used for reading comma-separated data from a file. The optional separator argument specifies the character to separate fileds. If left out, a comma is used. fgets(resource file, integer length) : returns a string that reads from a file. It will attempt to read as many characters – 1 as specified by the length value. A line-break character is treated as a stopping point, as is the end of the file. fwrite(resource file, string data, integer length) : writes a string to a file. The length argument is optional and sets the number of bytes to write.

User Defined Functions (1) Functions are re-usable blocks of code that can referenced over and over again. Arguments can be passed to functions and values can be returned by them. -arguments & return values can be passed by value or reference -PHP can create functions dynamically at run-time (Lambda –Style) -References to functions can be held in variables (or arrays) - allowing functions to be a passed as arguments to other functions - Declaring a function - functions are declared using the function statement, a name and parenthesis () e.g. function my_function() {…..} - functions can accept any number of arguments and these are separated by commas inside the parenthesis e.g. function my_function($arg1, $arg2) {…..}

the following simple function prints out any text passed to it as bold <?php function print_bold($text){ print(" $text "); } print("This Line is not Bold \n"); print_bold("This Line is Bold"); print(" \n"); print("This Line is not Bold \n"); ?> User Defined Functions (2) run code

Calculator example (from last weeks workshop) <?php function calculate($x, $y, $op) { switch($op) { case '+': $prod = $x + $y; break; case '-': $prod = $x - $y; break; case '*': $prod = $x * $y; break; case '/': $prod = $x / $y; break; } return $prod; } $x = 33; $y = 77; $op = '*'; $prod = calculate($x, $y, $op); echo "$x $op $y = $prod"; ?> User Defined Functions (3) run code

- the return statement - at some point the function will finish and is ready to return control to the caller - execution then picks up directly after the point the function was called - it is possible to have multiple return points from a function (but this will reduce code readability) - if a return statement includes an expression, return(expression), the value of the expression will be passed back - see calculator example on previous page & below <?php function makeBold($text){ $text = " $text "; return($text); } print("This Line is not Bold \n"); print(makeBold("This Line is Bold"). " \n"); print("This Line is not Bold \n"); ?> User Defined Functions (4)

- values and references - for most data types, return values are passed by value - for objects, discussed next week, return values are returned by reference - the following function creates a new array of 10 random numbers between 1 and 100 and passes it back as a reference <?php function &get_rand_array() { $a = array(); for($i=0; $i<10; $i++) { $a[] = rand(1,100); } return($a); } $my_new_array = &get_rand_array(); print_r($my_new_array); ?> User Defined Functions (5) run code

User Defined Functions (6) - scope - scoping is way of avoiding name clashes between variables in different functions - each code block belongs to a certain scope - variables within functions have local scope and are private to the function - variables outside a function have a global scope <?php $a = 1; // global scope function test(){ echo $a; // reference to local scope variable } test(); ?> The above example will output nothing because the $a inside the function has local scope

- the global keyword can be used to access variables from the global scope within functions <?php $a = 1; $b = 2; function sum(){ global $a, $b; $b = $a + $b; } sum(); echo $b; ?> - The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function. (Is it a good idea to use globals in this way?) User Defined Functions (7)

- arguments - functions expect arguments to be preceded by a dollar sign ($) and these are usually passed to the function as values - if an argument has a & sign in front - it is treated as a reference - the following example shows an argument passed as reference <?php function strip_commas(&$text){ $text = str_replace(",", "", $text); } $my_number = "10,000"; stripCommas($my_number); print($my_number); ?> User Defined Functions (8)

-default values - a function can use a default value in an argument using the = sign to precede the argument - consider the following example <?php function setName($FirstName = "John", $LastName = "Smith"){ return "Hello, $FirstName $LastName!\n"; } ?> - So, to greet someone called John Smith, you would just use: setName(); - To greet someone called Tom Davies, you would use: setName("Tom", "Davies"); - To greet someone called Tom Smith, you would use: setName("Tom"); User Defined Functions (9)

recursive functions (1) - recursive functions are functions that call themselves (self-calling) or to be sung to the tune of "When the Moon Hits Your Eye": "When a function calls a function in a Turing machine... that's recu-u-u-u-ursion!" or to put it simply: recursion means anything that references itself. -compare with iteration -example of iteration (print out all the values of an array) <?php for ($i = 0; $i < sizeof($array); $i++) { print $array[$i]; }sizeof ?> User Defined Functions (10)

recursive functions (2) - Mathematically speaking, a factorial (denoted by "!") is the result of a number multiplied by all positive integers less than that number. Non- integer and negative values are considered undefined. Zero factorial (0!), however, is defined as 1. e.g. 6! = 6 * 5 * 4 * 3 * 2 * 1 or 720 <?php function factorial($number) { if ($number < 2) { return 1; } else { return ($number * factorial($number-1)); } } print factorial(6); ?> User Defined Functions (11) run code

anonymous functions (run-time or dynamically created functions) - it is possible for PHP to use the value of an input (e.g. from a form) and change the definition of a function based on the input - example using calculator (last week’s workshop) <?php $add = create_function('$a,$b', 'return $a + $b;'); $subtract = create_function('$a,$b', 'return $a - $b;'); $multiply = create_function('$a,$b', 'return $a * $b;'); $divide = create_function('$a,$b', 'return $a / $b;'); extract($_GET); $fn = ${$op}; echo "$x $op $y = ". $fn($x,$y); ?> - Note the above example also illustrates how you can store a function name in a variable. User Defined Functions (12)

DB connectivity and processing forms processing sessions & cookies next week …