Download presentation
Presentation is loading. Please wait.
Published byMatilda Stafford Modified over 9 years ago
1
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
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 20-30 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
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
4 Calling Functions Typically we include functions at the end of code Welcome to my web page! "; … nav_bar(); function nav_bar() { … } ?>
5
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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");
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.