1 / 20

ITM 352 Functions

ITM 352 Functions. 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

manuelac
Download Presentation

ITM 352 Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ITM 352Functions

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

  4. identifier parameters Calling a Function • All PHP functions are designated by <identifier>(<parameters>) • e.g. phpinfo(), rand(1,10) • Function names are not case sensitive • Full interface for a function: • <return type><identifier> ( <parameters> )

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

  6. Parameter 2: max (int) Parameter 1: min (int) 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);

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

  8. 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 andreturna 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. 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";

  10. 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 … function name function signature function description

  11. ITM 352Creating Functions

  12. 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 <identifier> ( <parameters> ) { // function operations (code statements) here return <expression> } • The way you define a function defines the functions interface (or how it is expected to be used)

  13. function square($num) { $answer = $num * $num; return $answer; } To call the function: $quantity = 3; $myvar = square ($quantity); $myvar will contain the value 9 Function Syntax and Example function funcname($var1, $var 2...) { statement 1; statement 2; statement 3; ... return $retval; } 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. 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!!! DO NOT 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. 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. <?php function deposit($amount) { $balance = $balance + $amount; echo "New balance is $balance <BR>"; } $balance = 600; deposit(50); echo "Balance is $balance"; ?> What will this program print? Why? Scope of Variables – 2

  17. 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<BR>"; swapTwoValues($var1, $var2); echo "\$var1 is $var1 and \$var2 is $var2"; What would happen if we used $a and $b instead?

  18. 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. 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. 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<BR>"; swapTwoValues($var1, $var2); echo "\$var1 is $var1 and \$var2 is $var2";

More Related