1 Chapter 4 – Breaking It Up: Functions spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

PHP I.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
Introduction to PHP MIS 3501, Fall 2014 Jeremy Shafer
1 Programmer-Defined Functions Functions allow program modularization Variables declared in function are local variables Only known inside function in.
1 Chapter 5 – Handling HTML Controls in Web Pages spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
Objectives Using functions to organize PHP code
1 PHP Statement Constructs Server Scripting. 5-2 Basic Statement All Statements end in a semicolon. Statements are delimited from the HTML code by enclosing.
PHP –Writing Reusable Code 10 March 2006 Adina Crainiceanu IT420: Database Management and Organization.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
VBA Modules, Functions, Variables, and Constants
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Guide To UNIX Using Linux Third Edition
Review of C++ Programming Part II Sheng-Fang Huang.
PHP: Hypertext Processor Fred Durao
August Chapter 1 - Essential PHP spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
Introduction to PHP and Server Side Technology. Slide 2 PHP History Created in 1995 PHP 5.0 is the current version It’s been around since 2004.
1 Chapter 6 – Creating Web Forms and Validating User Input spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Form Handling.
Functions & Objects IDIA 618 Spring 2012 Bridget M. Blodgett.
IE 212: Computational Methods for Industrial Engineering
PHP Flow Control Loops, Functions, Return, Exit, Require, Try...Catch Software University SoftUni Team Technical Trainers.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
NMED 3850 A Advanced Online Design January 26, 2010 V. Mahadevan.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
1 Chapter 9 – Cookies, Sessions, FTP, and More spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
COMP An Introduction to Computer Programming : University of the West Indies COMP6015 An Introduction to Computer Programming Lecture 05.
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.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (there is an audio component to this eLesson) © Dr.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
Intro to PHP IST2101. Review: HTML & Tags 2IST210.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
1 Chapter 7 – Object-Oriented Programming and File Handling spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
JavaScript, Fourth Edition
NMD202 Web Scripting Week5. What we will cover today PHP & MySQL Displaying Dynamic Pages Exercises Modifying Data PHP Exercises Assignment 1.
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter 6 Methods Chapter 6 - Methods.
Creating PHP Pages Chapter 5 PHP Structure and Syntax.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
1 PHP Intro PHP Introduction After this lecture, you should be able to: Know the fundamental concepts of Web Scripting Languages in general, PHP in particular.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
Session 2: PHP Language Basics iNET Academy Open Source Web Development.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
5 th and 4 th ed: Chapters 9, 10, 11 SY306 Web and Databases for Cyber Operations SlideSet #7: JavaScript Functions and Arrays.
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,
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 7 Using Methods.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
A variable is a name for a value stored in memory.
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
PHP Functions, Scope MIS 3501, Fall 2015 Jeremy Shafer
6 Chapter Functions.
PHP.
Objectives In this chapter, you will:
Basics (Cont...).
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

1 Chapter 4 – Breaking It Up: Functions spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology Radford University

2 Functions In addition to the many built-in functions that we've seen in PHP, user-defined functions can be easily built User-defined functions - it's the best way break code in manageble sections - when scripts are longer than statements they should probably be broken into functions - functions limit variable scope if you have a 2000 line script and you use a variable named $counter at the beginning, then you forget and use another variable named $counter near the end, they will be the same variable and unintended side effects and bugs will result - functions promote reusability - functions improve reliability

3 Creating a Function To define a function function function_name([arg_list…]) { } say all your web pages have a navigation bar at the top function nav_bar() { echo " "; echo " "; echo " Home "; echo " Site Map "; echo " Help ; echo " ";

4 Calling Functions Typically we include functions at the end of code Welcome to my web page! "; … nav_bar(); function nav_bar() { … } ?>

5 Passing data to Functions nav_bar("Big Company","© 2005"); function nav_bar($text, $copyright) { … more statements here … echo " $text "; echo " $copyright "; } if you fail to pass an argument to a function, you'll get an error like: PHP Warning: Missing argument 1 for nav_bar in C:\php\t.php on line 5 you can provide a default value when you define a function as in: function greeting($text = "Hi") now if you don't provide a value, then the default value will be used

6 Passing Arrays to Functions Arrays can be passed to functions as arguments <?php $fruits[0] = "apples"; $fruits[1] = "oranges"; array_echoer($fruits); #call to function function array_echoer($arr) { for ($ind=0;$index<count($arr);$ind++) { echo "Element $ind: ","$arr[$ind]", "\n"; } }

7 Passing Arguments by Reference Pass-by-value is the default method of passing argument values in PHP (a copy of the value of the variable is made and stored in local memory for the function). Meaning what? What if we want to pass by reference, so if changes are made to a value in the function they are reflected in the calling program? $string = "no "; add_text($string); echo $string; function add_text(&$text) { $text.= "worries"; } in this function the variable $string is passed by reference, what would the output be if it was not passed by reference?

8 Variable-Length Argument Lists You can pass a variable number of arguments to functions. For example, here's a function named joiner that joins any number of strings together. joiner("No","worries"); joiner("Here's", "a", "longer", "string"); There are three PHP functions to retrieve the number of arguments and the value of each argument passed to a function. func_num_args -- returns the number of arguments passed func_get_arg -- returns a single argument func_get_args -- returns all arguments in an array.

9 Varialble_Length Argument Lists (cont) function joiner() { $text = ""; $arg_list = func_get_args(); for ($ct=0;$ct<func_num_args();$ct++) { $text.= $arg_list[$ct]. " "; } } Returning values from functions just use the return statement function square($val) { return ($val * $val); } call statement -- $sqval = square($num); argpass.phpargpass.php

10 Return Statements PHP does allow the use of multiple return statements in a single function. When a return statement is executed in a function, execution of the function is over. function check_temp($temp) { if ($temp > 65 && $temp<85) { return TRUE; } return FALSE; } Why is no else clause needed in this function? Is this good programming?

11 Returning Arrays In PHP the return statement can return arrays as well as scalar values. function array_dbl($arr) { for ($ct=0;$ct<count($arr);$ct++) { $arr[$ct] *= 2; } return $arr; } to call -- $pricearray = array_db($pricearray); Exercise -- Implement an array doubler in php that outputs an html document that shows the original array values and the doubled array values.

12 Returning Lists Lists are another way to return multiple values from a function. function arraydbl($arr) { for ($ctr=0;$ctr<count($arr);$ct++) { $arr[$ctr] *= 2; } return $arr; } $loarr = array(2,4,6,8); list($first, $second, $third) = arraydb($loarr); even if you only use the first few elements of an array, it will work you can't return a list directly from a function as in: return list($one, $two);

13 Using Variable Scope breaking code into functions helps with: testing & reliability, code reuse, documentation (maintainability), and most definitely tends to reduce side effects due to improper variable scope. "; local_scope(); echo "after fn, \$val = ", $val, " "; function local_scope() { $val = 20000; echo "in fn, \$val = ", $val, " "; } ?> function variables are local scope --

14 Global Access you can access script level (global) variables) inside a function, but you must declare the variable global "; global_scope(); echo "scr level \$val = ",$val," "; function global_scope() { global $val; $val += 2; echo "in fn \$val =", $val, " "; } echo "scr level \$val = ",$val," ";

15 Static Variables local variables in functions are reset to their starting values each time the function is called you can have function variables retain their values between function executions by declaring a local variable as static "; echo "count = ", counter(), " "; echo "count = ", counter(), " "; echo "count = ", counter(), " "; function counter() { static $countvar = 0; $countvar++; return $countvar; } ?>

16 Variable Functions a variable can hold the name of a function, the function can be called by including parentheses after variable. this allows the program to determine which function is called at run time $fn_var = "apples"; $fn_var(); $fn_var = "oranges"; $fn_var(); function apples() { … } function oranges() { … } -- think about determining which function to call based on input

17 Conditional & Sub Functions some functions may be defined inside an if statement or in some other conditional clause in this case, since PHP is an interpreted language, you have to make sure the conditional statement is executed before the function is executed functions can be nested in PHP remember, like conditional functions, the internal (nested function) doesn't exist until the enclosing function is executed

18 Include Files include files allow you to reuse functions stored in separate files example define some constants in a separate file "; ?> login functions that are used by a number of applications, database login values and passwords, etc.

19 Errors Returned from Functions if there's been an error in a function, that function returns a value of FALSE intentionally. you can also write functions that will return false if there's an error function reciprocal($val) { if ($val != 0) { return 1/$val; } else { return FALSE; } } one way of handling a return value of FALSE is to use the PHP die function $filename = "nonfile"; $file = fopen($filename, "r") or die("Cannot open file");