PHP: Functions

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Functions

Aims:

Self-processing, sticky, and validates user data

<?php 
 $width = '';
 $height = '';
 $errors = array();
 $area = '';
 // Check whether this script is showing the user the form for the first time or 
 // whether this script is being called after the user has submitted the form
 if ( isset($_GET['submitted']) ) 
 {
    $width = $_GET['width'];
    $height = $_GET['height'];
    // Validate the user-supplied width and height
    if ( ! is_numeric($width) || $width <= 0 ) 
    {
       $errors[] = 'The width must be a positive number.';
    }
    if ( ! is_numeric($height) || $height <= 0 ) 
    {
       $errors[] = "The height must be a positive number.";
    }
    // Calculate the area, if there are no errors
    if ( count($errors) == 0 ) 
    {
       $area = $width * $height;
    }
 }
?>

<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<!DOCTYPE html 
 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>Compute the area of your screen</title>
  <link rel="stylesheet" type="text/css" href="formlayout.css" />
</head>

<body>

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="get">

  <fieldset>
   <legend>Enter the dimensions of your screen</legend>
   <p>
    <label for="widthField">Width (inches):</label>
    <input type="text" name="width" id="widthField" 
           value="<?php echo $width; ?>"
           size="4" maxlength="4" />
   </p>
   <p>
    <label for="heightField">Height (inches):</label>
    <input type="text" name="height" id="heightField" 
           value="<?php echo $height; ?>"
           size="4" maxlength="4" />
   </p>
 
   <div id="errors">
    <?php
	 // Output each error message, if any
	 foreach ($errors as $error)
	 {
	    echo "<p>ERROR: {$error}</p>";
	 }
    ?>
   </div>

   <p>
    <input type="submit" name="submitted" value="Calculate area" />
   </p>
  </fieldset>

  <fieldset>
   <legend>Area of your screen</legend>
   <p>
    <label for="areaField">Area (square inches):</label>
    <input type="text" name="area" id="areaField" 
           value="<?php echo $area; ?>"
           size="5" maxlength="5"
           disabled="disabled" />
   </p>
  </fieldset>

</form>

</body>
</html>

Calling functions

Defining functions

Two alternative versions

function is_pos_num($x) 
{
   return (is_numeric($x) && $x > 0) ? true : false;
}

function is_pos_num($x) 
{
   if ( is_numeric($x) && $x > 0 ) 
   {
      return true;
   }
   else 
   {
      return false;
   }
}

Calling the function

if ( ! is_pos_num($width) ) 
{
   $errors[] = 'The width must be a positive number.';
}
if ( ! is_pos_num($height) ) 
{
   $errors[] = "The height must be a positive number.";
}

Return values

A useful function? Definition

function echo_form_field($labelTxt, $name, $value, $isDisabled) 
{
   $id = $name . 'Field';
   echo "<p>";
   echo "<label for=\"$id\">$labelTxt</label>";
   echo "<input type=\"text\" name=\"$name\" id=\"$id\" "; 
   echo "value=\"$value\" ";
   if ($isDisabled) 
   {
      echo "disabled=\"disabled\"";
   }
   echo "/>";
   echo "</p>";
}

A useful function? Calling it

<?php 
 echo_form_field("Width (inches):", "width", $width, false);
 echo_form_field("Height (inches):", "height", $height, false);
 echo_form_field("Area (square inches):", "area", $area, true);
?>

Variable scope

Example

What does this echo to its output?

<?php
 function my_function() 
 {
    $a = $a + 5;
 }

 $a = 6;
 my_function();
 echo $a;
?>

Example

What does this echo to its output?

<?php
 function echo_section_header($title) 
 {
    $sectionNum++;
    echo "<h2>Section $sectionNum: $title</h2>";
 }

 $sectionNum = 0;
 echo_section_header('Introduction');
 echo_section_header('19th Century Lobotomies');
?>

Can it be fixed? Yes: Advanced material I

<?php
 function echo_section_header($title) 
 {
    global $sectionNum;
    $sectionNum++;
    echo "<h2>Section $sectionNum: $title</h2>";
 }

 $sectionNum = 0;
 echo_section_header('Introduction');
 echo_section_header('19th Century Lobotomies');
?>

Can it be fixed? Yes: Advanced material II

<?php
 function echo_section_header($title) 
 {
    static $sectionNum = 0;
    $sectionNum++;
    echo "<h2>Section $sectionNum: $title</h2>";
 }

 echo_section_header('Introduction');
 echo_section_header('19th Century Lobotomies');
?>

Functions: advanced issues

Functions: the benefits