Presentation is loading. Please wait.

Presentation is loading. Please wait.

20. Code Reuse and Functions Code Reuse with include()

Similar presentations


Presentation on theme: "20. Code Reuse and Functions Code Reuse with include()"— Presentation transcript:

1 20. Code Reuse and Functions Code Reuse with include()
include() takes pathname of a file with PHP code or HTML Includes the file contents where it’s called require() behaves just like include() except that, when there’s an error, besides producing a warning, it results in a fatal error Discuss only include()

2 Modularizing HTML include() lets us segment HTML document into parts
Several typically used in multiple documents HTML document (next slides), rendering below Content partitions into a a header (e.g. company title and logo) a menu of links to pages with specific info the specific page content a footer (e.g., a copyright notice and specific contact info)

3 Continued <html> <head>
<title>Aggie Consulting</title> <style type="text/css"> h1 { color: red; text-align: center; font-family: Arial, san-serif } td { background: cyan } p.footer { text-align: center } </style> </head> <body> Continued

4 Continued <!-- Page header -->
<table width="100%" border="0"> <tr> <td align='left'> <img src='AT.jpg' height='88' width='78' alt='A & T'> </td> <td><h1>A & T Consulting</h1></td> <td align='right'> </tr> </table> Continued

5 Continued <!-- menu --> <table width='100%'> <tr>
<td><a href='template.html'>Home</a></td> <td><a href=' <td><a href='services.html'>Services</a></td> </tr> </table> <!-- page content --> <p>Welcome to A&T Consulting, a leader in the industry.</p> <p>Check out our amazing offers!</p> Continued

6 <!-- page footer -->
<table width='100%'> <tr> <td> <p class='footer'>© A&T Consulting</p> <p class='footer'> Please direct questions to our <a href='legal.html'>legal services</a>. </p> </td> </tr> </table> </body> </html>

7 Modularize this document
Put CSS rules in separate file template.css file Include in the new document a link : <link rel='stylesheet' href='template.css' type='text/css'> Make separate .html documents for header, menu, and footer Not complete documents Page content is specific to the page—not factored out Names for included files: their roles followed by _inc and .html

8 Could use extension .php, but no need, no PHP script
Any extension works even though PHP is normally called only for .php files Compare with functions for reading files Some developers use special extension, e.g., .inc But, if such a file is stored in the document tree and a user loads it directly, sees the code in plain text Next slide: new top-level PHP script

9 <html> <head> <title>Aggie Consulting</title> <link rel='stylesheet' href='template.css' type='text/css'> </head> <body> <?php include( 'header.html' ); include( 'menu.html' ); ?> <p>Welcome to A&T Consulting, a leader in the industry.</p> <p>Check out our amazing offers!</p> include( 'footer.html' ); </body> </html>

10 Exploit included files for pages with same look and feel as the home page
services.php: content of original services.html but with standardized header, menu, and footer: Just the body <body> <?php include( 'header.html' ); include( 'menu.html' ); ?> <p>We do just about anything you want.</p> include( 'footer.html' ); </body>

11 legal.php, a similar update of legal.html:
<head> <title>Legal Services</title> <link rel='stylesheet' href='template.css' type='text/css'> </head> <body> <?php include( 'header.html' ); include( 'menu.html' ); ?> <p> Come see us in the basement of McNair Hall MWF after class and some Saturday mornings (but not too early). </p> include( 'footer.html' ); </body> </html>

12 We’ve assumed included files are in same folder as the current script
Pathname argument of include() could indicate a file in a different folder (relative to folder with current script) In the php.ini file, can specify an include path Files for including are 1st sought in each include-path entry relative to current working directory (for relative pathnames) Then in directory of current script

13 In contrast, require() produces a fatal error
If the file can’t be included, include() returns false and a warning is issued Make our example more robust by checking for failure and handling it gracefully—e.g., if ( ! include( 'header.html' ) ) echo "<h1>A&T Consulting</h1>"; If file header.html isn’t found, result is ugly but essential info still provided In contrast, require() produces a fatal error Often preferred since it doesn’t let (possibly unnoticed) errors pile up

14 PHP Script in an Included File
Any code inside an included file to be executed as PHP code must be enclosed within PHP tags E.g., script that includes greeting_inc.php Request provides values for form variables first, last, age Screenshot where first is ‘Al’, last is ‘Smith’, age is 33 Listing on next slide

15 <?php $first = $_POST['first']; $last = $_POST['last']; $age = $_POST['age']; ?> <html> <head> <title>Using include()</title> </head> <body> include( 'greeting_inc.php' ); echo "\n<p>Your age is $age.</p>\n"; </body> </html>

16 Listing of greeting_inc.php:
echo "<h3>Hello $first $last!</h3>\n"; ?> <p>Welcome to our webpage!</p> PHP tags are obligatory greeting_inc.php assumes it will be included in a script where variables $first and $last have reasonable values

17 Can include different files depending on form-data values
E.g., script that includes greeting_old_inc.php if user over 65 Else (as in previous example) greeting-inc.php Listing of body on next slide Screenshot when $age is 67

18 Listing of greeting_old_inc.php
<body> <?php if ( $age > 65 ) include( 'greeting_old_inc.php' ); else include( 'greeting_inc.php' ); echo "\n<p>Your age is $age.</p>\n"; ?> </body> Listing of greeting_old_inc.php echo "<h2>Good day, $first $last!</h2>\n"; <p style='font-size: 140%'> Welcome to our electronic information sheet! </p>

19 Can execute a return() inside an included file
Terminate processing in that file, returns to script that included it Also returns a value from included files E.g., script that includes a file greeting_diverse_inc.php Returns a string giving the user’s age classification String saved in variable $group <body> <?php $group = include( 'greeting_diverse_inc.php' ); echo " <h3>The page especially for $group people</h3>\n"; ?> </body>

20 greeting_diverse_inc.php returns ‘young’, ‘middle-aged’, or ‘elderly’
Outputs a greeting as before, then checks if $age < 30 If so, returns ‘young’—and supplies no more HTML Otherwise, outputs a paragraph with the age and checks if the $age ≤ 65 If so, outputs a farewell and returns ‘middle-age’ Else it outputs a different farewell and returns ‘elderly’ Listing on next slide

21 <?php echo "<h3>Hello $first $last!</h3>"; ?> <p>Welcome to our webpage!</p> if ( $age < 30 ) return( 'young' ); echo " <p>Your age is $age.</p>\n"; if ( $age <= 65 ) { echo " <p>See you again soon!</p>\n"; return( 'middle-aged' ); } else { echo " <p>Please return again.</p>\n"; return( 'elderly' );

22 The comparison involves a syntax error
Change this so the comment about the special group is restricted to the middle-aged 1st attempt: if ( include( 'greeting_diverse_inc.php' ) == 'middle-aged' ) echo " <h3>The page especially for ". "middle-aged people</h3>\n"; The comparison involves a syntax error

23 Can write syntactically correct version as
Since include() is a special language construct, don’t need “()” around its argument Can write syntactically correct version as if ( (include 'greeting_diverse_inc.php' ) == 'middle-aged' ) echo " <h3>The page especially for ". "middle-aged people</h3>\n";

24 Defining Functions Function Basics
A function definition starts with keyword function followed by the function name a parameter list in parentheses a block of code (function body) Parameter list consists of formal parameters separated by commas Formal parameters have same formation rules as variables By default, function arguments are passed by value A function name is a valid PHP identifier not preceded by a $

25 A function is called with its name followed by the list of actual parameters in parentheses
Function names are case-insensitive—but poor style to change the case pattern PHP doesn’t support function overloading And can’t undefine or redefine previously-declared functions So only one function declaration introducing a given function name in a script (including included files) A function can be referenced before it’s defined— except when conditionally defined or defined in another function—later

26 E.g., script defines function hello with 2 formal parameters
Outputs an h3 element (containing values of the parameters) and a p element hello is called in the body, passing form data Screenshot of rendering of HTML produced passed ‘Al’ and ‘Smith’ Listing on next slide

27 <?php function hello( $first_name, $last_name ) { echo " <h3>Hello $first_name $last_name!</h3>\n"; echo "<p>Welcome to our webpage!</p>\n"; } $first = $_POST['first']; $last = $_POST['last']; ?> <html> <head> <title>Using Functions</title> </head> <body> hello( $first, $last ); </body> </html>

28 Next script shows that function definition can
go anywhere (not a good idea) occur in several chunks of PHP code—then the pure HTML between { in 1 chunk and } in the next is part of the function body Output identical to that of the previous but adds a paragraph <?php $first = $_POST['first']; $last = $_POST['last']; ?> <html> <head> <title>Using Functions</title> </head> <body> Continued

29 <?php hello( $first, $last ); function hello( $first_name, $last_name ) { echo " <h3>Hello $first_name ". "$last_name!</h3>\n"; ?> <p>Welcome to our webpage!</p> echo "<p>Come back again, $first_name.</p>\n"; } </body> </html>

30 Values returned with optional return()
Since it’s a special language construct, () are optional Executing it immediately terminates the function Returns control to where it was called Argument to return() is optional Any type may be returned (including arrays) E.g., the following function forms and returns the sum of the numbers in an array Like built-in array_sum()

31 function sum_array( $arr ) {
foreach ( $arr as $num ) $sum += $num; return $sum; } Next: Return an array identical to the one passed in but each value incremented by 1 function array_inc( $arr ) { foreach ( $arr as &$num ) $num ++; return $arr;

32 Multiple values can’t be returned
Get similar effect by returning an array and assigning it to a list E.g., consider function ops( $num1, $num2 ) { return array( $num1+$num2, $num1-$num2, $num1*$num2, ( $num2 ? $num1/$num2 : NULL ) ); } Assign the 4 values returned in array to 4 variables with list( $sum, $diff, $prod, $quot ) = ops( 6, 2 );

33 Pass and Return by Reference
By default, function arguments are passed by value A function can modify the value of a variable by passing a reference to it E.g., given function inc( $num ) { $num ++; } can use it to increment the value of $x: inc( &$x );

34 E.g., if we redefine the above as
To have a argument always passed by reference, prepend an & to the formal parameter E.g., if we redefine the above as function inc( &$num ) { $num ++; } then inc( $x ); increments value of $x

35 Arrays too are passed by value Changes not communicated back E.g.,
function setVal( $ar, $key ) { $ar[$key] = 95; } $arr = array( 'Ed' => 58, 'Sue' => 72, 'Al' => 91 ); setVal( $arr, 'Sue' ); leaves the value associated with ‘Sue’ as 72 But if we change the function header to function setVal( &$ar, $key ) the value associated with ‘Sue’ is changed to 95

36 Version of array_inc() without a return, but passing the array by reference.
function array_inc1( &$arr ) { foreach ( $arr as &$num ) $num ++; }

37 And prepend function name and call with & E.g.,
To return a reference from a function, use a reference parameter and return a reference And prepend function name and call with & E.g., function &getVal( &$ar, $key ) { $vl =& $ar[$key]; return $vl; } $arr = array( 'Ed' => 58, 'Sue' => 72, 'Al' => 91 ); then $val =& getVal( $arr, 'Sue' ); sets $val to a reference to the variable content associated with key ‘Sue’, and $val = 82; causes $arr['Sue'] to be 82

38 Collapsing 2 statements in getVal() into the following statement causes a syntax error
return & $ar[$key];

39 Default Parameter Values and Variable-length Parameter Lists
First cover default parameter values Assign a formal parameter a default value in the parameter list All parameters with default values appear after all parameters without Example: function outputting a sequence of numbers Begins with the value of the 2nd parameter, $start Ascends by increments given by 3rd parameter, $incr Stops at the value of the 1st parameter, $stop Defaults: $start=0 and $incr=1

40 count_up( 10, 4, 2 ) produces 4 6 8 10 count_up( 10, 5 ) produces
function count_up( $stop, $start=0, $incr=1 ) { if ( $stop < $start || $incr < 1 ) { echo "<p>Arguments out of range</p>"; return; } for ( $i=$start; $i<=$stop; $i+=$incr ) echo "$i "; count_up( 10, 4, 2 ) produces count_up( 10, 5 ) produces count_up( 10 ) produces

41 If a value is supplied for an optional argument in a call,
then values must be supplied for all optional arguments corresponding to parameters in the parameter list before the parameter corresponding to the argument in question Missing an optional argument would mess up the actual- formal parameter correspondence E.g., if we provide a value for $incr in count_up(), must provide a value for $start

42 A default value must be a constant (not, e. g
A default value must be a constant (not, e.g., a variable or a function call) But can have arrays and NULL as default values E.g., function expects as 1st argument the name of a farmer as 2nd argument an array of names of animals on his farm By default, animal names are ‘pigs’ and ‘sheep’

43 outputs animals( 'Old MacDonald',
function animals( $farmer, $beasts=array( 'pigs', 'sheep' ) ) { if ( is_null( $beasts ) ) { echo "There are no animals on $farmer's farm."; return; } $kind = array_pop( $beasts ); if ( sizeof( $beasts ) == 0 ) echo "On $farmer's farm, there are $kind."; else echo "On $farmer's farm, there are ". join( ", ", $beasts )." and $kind."; animals( 'Old MacDonald', array( 'pigs', 'sheep', 'cattle', 'horses' ) ); outputs On Old MacDonald's farm, there are pigs, sheep, cattle and horses.

44 sets $beasts to NULL, outputs
animals( 'Smith' ); uses default, outputs On Smith's farm, there are pigs and sheep. animals( 'Miller', NULL ); sets $beasts to NULL, outputs There are no animals on Miller's farm.

45 Now: variable number of arguments
No special syntax But some built-in functions are called in the function body func_get_args() returns an array of copies of the argument values in the call But not defaults func_num_args() returns the number of arguments func_get_arg( Integer ) returns a copy of the argument at position Integer in the list of arguments 1st argument is at position 0 Can’t return default values

46 Can be called with any number of arguments
Example, duplicating built-in max(), defined with an empty parameter list Can be called with any number of arguments function my_max( ) { $nums = func_get_args(); $size = func_num_args(); if ( $size == 0 ) return NULL; $biggest = $nums[0]; for ( $i=1; $i<$size-1; $i++ ) if ( $nums[$i] > $biggest ) $biggest = $nums[$i]; return $biggest; }

47 With a variable number of arguments, can still have parameters in the parameter list
Their values are duplicated in the array returned by func_get_args() E.g., in definition of my_max(), the 1st argument was used to initialize $biggest Achieve the same by including $biggest in parameter list Eliminate the statement initializing $biggest Function header is then function my_max( $biggest )

48 Loop control variable still initialized to 1
$nums still contains the list of all arguments But my_max() must now be called with at least 1 argument General rule: A function can be called with more, but not fewer, arguments than parameters in the parameter list

49 Variable Scope The scope of a variable is the context it’s defined in
This scope spans included and required files as well—e.g., in <?php $a = 1; include 'b.inc'; ?> the $a variable is available in the included b.inc script   A user-defined function introduces a local scope Any variable used inside a function is by default limited to the local function scope

50 Do so using the global keyword—e.g.,
In PHP (unlike C++ and Java), global variables must be declared global inside a function if they’re used in it Do so using the global keyword—e.g., <?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; ?> This outputs 3 By declaring $a and $b global in the function, all references to them refer to the global versions

51 Rewrite the last example as
A 2nd way to access variables from the global scope is to use the special PHP-defined $GLOBALS array Rewrite the last example as <?php $a = 1; $b = 2; function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } Sum(); echo $b; ?> The $GLOBALS array is an associative array with the name of the global variable as the key and the contents of that variable as the value of the array element

52 The superglobal variables are
$GLOBALS exists in any scope—it’s a superglobal The superglobal variables are $GLOBALS $_SERVER (an array containing info such as headers, paths, and script locations, created by the web server) $_GET $_POST $_FILES $_COOKIE $_SESSION $_REQUEST (contains the contents of $_GET, $_POST, $_COOKIE) $_ENV (an associative array of variables passed to the current script from the environment it’s running under)

53 E.g., the following always works (as long as 'name' was sent by the requesting form)
<?php function test_global() { echo $_POST['name']; } ?>

54 Static Variables A static variable exists only in a local function scope Doesn’t lose its value when program execution leaves this scope When the function is called again, the static variable has the value it had at the end of the last execution of the function Must be initialized to a constant value (not an expression) when declared This is executed only the 1st time the function is called

55 Example <?php function test() { static $a = 0; echo $a . " "; $a++; } test(); ?> outputs 0 1 2 $a is initialized only in the 1st call Every time test() is called, it prints the value of $a and increments it

56 Static variables provide one way to deal with recursive functions—e. g
<?php function test() { static $count = 0; $count++; echo $count." "; if ($count < 5) { test(); } ?> outputs

57 Static declarations (initializations) are resolved at compile-time
In the declaration of a static variable, trying to assign to it a value that’s the result of an expression causes a parse error—e.g., <?php function foo(){ static $int = 0; // correct static $int = 1+2; // wrong (an expression) static $int = sqrt(121); // wrong ( an expression) ... } ?>


Download ppt "20. Code Reuse and Functions Code Reuse with include()"

Similar presentations


Ads by Google