Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 ITM 3521 ITM 352 Functions

2 ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It acts on a set of values given to it (parameters)  It may return a single value (return-value)  Functions are very useful for  Repeated tasks in multiple locations  Sharing useful code  Saving execution time  Modularization: Dividing up the task

3 ITM 3523 Functions  We've already made use of several functions!  Can you think of some?  Some functions are built in to PHP, some are added from code libraries, some you will define Do Lab #1

4 ITM 3524 Calling a Function  All PHP functions are designated by ( )  e.g. phpinfo(), rand(1,10)  Function names are not case sensitive  Full interface for a function:  ( ) identifier parameters

5 ITM 3525 Calling a Function  Functions are used by calling them <?php … $commission = $sales * $rate; echo round($commission,2); … ?> the "call"

6 ITM 3526 Passing Values into a Function: Parameters  Some Functions can be more flexible (therefore useful) if we pass them input values to use in their operations  Input values for functions are called passed values or parameters  Parameters must be specified inside the parentheses () of the function, and must be of the expected data type, in the expected order as defined by the function's interface rand(int min, int max) rand(1,10); Parameter 1: min (int) Parameter 2: max (int)

7 ITM 3527 Passing Variables  Any legal expression can be used as a parameter (recall that an expression returns a value) rand(44%3, 2*$max*$max);  It is very common to use a variable for a parameter (recall: a variable by itself is an expression – it returns the value of the variable) rand($minGuess,$maxGuess); substr($name,1,$i); Do Lab #2

8 ITM 3528 Return Values of Functions  Some Functions just perform an action (e.g. read in a value from the keyboard, switch to a web page) and do not return a value  Most functions perform an action and return a single value  Return types may be:  a primitive data type, such as int, float, boolean, etc.  a compound type such as array, object, etc.  void if no value is returned  Return values are how a function passes information back after it is called and after it performs its operations.

9 ITM 3529 Return Values of Functions  You can use a function with a returned value any place where it is legal to use an expression,  $guess = rand(1,10);  3.14159*rand(1,10);  echo phpinfo();  $yummy = "piece of ". substr("piece",0,3);  if( is_int($guess) ) …  A common return value for a function is boolean  true is the function operations were successful with no problems  false if the function failed to perform its task if( !writeFile() ) echo "file not written"; Do Lab #3

10 ITM 35210 Function Documentation  Functions are documented not only with a description of the function, but also with a interface that shows the return value type, the name of the function, and the required and optional arguments: type function_name (type arg1, type arg2 [,type optional_arg])  PHP functions often document functions this way: printf (PHP 3, PHP 4 ) printf -- Output a formatted string Description void printf ( string format [, mixed args]) Outputs a string by using format and the given arguments …  You can look up functions using the book index, Appendix A function categories, or PHPed's help function name function signature function description Do Lab #4

11 ITM 35211 ITM 352 Creating Functions

12 ITM 35212 Defining Functions  A very important aspect of PHP is the ability to create your own functions. You will find out how useful this is later.  You declare a function with the function keyword in front of a identifier and function parameter set and a code-block: function ( ) { // function operations (code statements) here return }  The way you define a function defines the functions interface (or how it is expected to be used)

13 ITM 35213 Function Syntax and Example function funcname($var1, $var 2...) { statement 1; statement 2; statement 3;... return $retval; } function square($num) { $answer = $num * $num; return $answer; } To call the function: $quantity = 3; $myvar = square ($quantity); $myvar will contain the value 9 NOTE that the variable names do not need to be the same; the order of variables passed is what will matter inside the function!

14 ITM 35214 Global vs. Local Variables  Variables defined inside a function (or passed in) are "local variables" and are only available within functions  after exiting the function the variable ceases to exist!!!  Variables defined outside of a function are generally not available inside a function. So variables should be passed into a function as arguments!!!  Global variables are accessible both in and out of functions  NOT recommended!!! DON’T DO IT!!!!  Where the variable is active (alive) is known as its "scope"  use global and static to modify this  also "passing by reference" will affect scope

15 ITM 35215 Scope of Variables  Inside a function is like an entirely new program.  Variables that you define within the function have "local" scope:  They don't exist before the function starts  They don't exist once the function has completed

16 ITM 35216 Scope of Variables – 2 <?php function deposit($amount) { $balance += $amount; echo "New balance is $balance "; } $balance = 600; deposit(50); echo "Balance is $balance"; ?> What will this program print? Why?

17 ITM 35217 Defining Functions function swapTwoValues($a, $b) { $tmp = $a; // save old value temporarily $a = $b; // copy second parameter into first $b = $tmp; // copy original first value into second } $var1 = 1; $var2 = 2; echo "\$var1 is $var1 and \$var2 is $var2 "; swapTwoValues($var1, $var2); echo "\$var1 is $var1 and \$var2 is $var2"; What would happen if we used $a and $b instead?

18 ITM 35218 Function Naming Conventions Good Programming Practice (we will look for this!)  Use verbs to name functions that do not return values or operate directly on variables  They usually perform an action e.g. sort(), print_table()  Use nouns to name functions that return a value  they create (return) a piece of data, a thing e.g. date()  Start function names with a lower case letter  phpinfo()  Use "_" to separate words  is_bool()  Use descriptive names  get_html_translation_table()

19 ITM 35219 Pass-By-Value vs. Pass-By-Reference  When a function is called, the value of each argument is copied (assigned) and used locally within that function  Variables used as arguments cannot be changed by a function!!!!!!!!!  One way to change a value of a passed in variable is to make use of return value: function doubler($value) { return 2*$value; } echo doubler($doubleUp); $doubleUp = doubler($doubleUp);

20 ITM 35220 Pass-By-Value vs. Pass-By-Reference  Sometimes it's more convenient to directly operate on a variable, so you pass in its reference (address): function swapTwoValues(&$a, &$b) { $tmp = $a; // save old value temporarily $a = $b; // copy second parameter into first $b = $tmp; // copy original first value into second } $var1 = 1; $var2 = 2; echo "\$var1 is $var1 and \$var2 is $var2 "; swapTwoValues($var1, $var2); echo "\$var1 is $var1 and \$var2 is $var2"; Do Lab #5


Download ppt "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."

Similar presentations


Ads by Google