Chapter 5. Using Functions and Session Variables

In This Chapter

  • Creating functions to manage your code's complexity

  • Enhancing your code by using functions

  • Working with variable scope

  • Getting familiar with session variables

  • Incorporating session variables into your code

PHP programs are used to solve interesting problems, which can get quite complex. In this chapter, you explore ways to manage this complexity. You discover how to build functions to encapsulate your code. You also learn how to use session variables to make your programs keep track of their values, even when the program is called many times.

Creating Your Own Functions

It won't take long before your code starts to get complex. Functions are used to manage this complexity. As an example, take a look at Figure 5-1.

Rolling dice the old-fashioned way

Before I show you how to improve your code with functions, look at a program that doesn't use functions so you have something to compare with.

The following rollDice.php program creates five random numbers and displays a graphic for each die:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/xml; charset=utf-8" />
    <title>rollDice1.php</title>
  </head>

  <body>
    <h1>RollDice 1</h1>
    <h2>Uses Sequential Programming</h2>
    <div>
    <?php
$roll = rand(1,6); $image = "die$roll.jpg"; print <<< HERE <img src = "$image" alt = "roll: ...

Get HTML, XHTML, & CSS All-in-One For Dummies®, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.