PHP Cookbook/Variables

From WikiContent

< PHP Cookbook(Difference between revisions)
Jump to: navigation, search
(Initial conversion from Docbook)
Current revision (13:36, 7 March 2008) (edit) (undo)
(Initial conversion from Docbook)
 
(One intermediate revision not shown.)

Current revision

PHP Cookbook


Contents

Introduction

Along with conditional logic, variables are the core of what makes computer programs powerful and flexible. If you think of a variable as a bucket with a name that holds a value, PHP lets you have plain old buckets, buckets that contain the name of other buckets, buckets with numbers or strings in them, buckets holding arrays of other buckets, buckets full of objects, and just about any other variation on that analogy you can think of.

A variable is either set or unset. A variable with any value assigned to it, true or false, empty or nonempty, is set. The function isset( ) returns true when passed a variable that's set. The only way to turn a variable that's set into one that's unset is to call unset( ) on the variable. Scalars, arrays, and objects can all be passed to unset( ). You can also pass unset( ) multiple variables to unset them all:

unset($vegetables);
unset($vegetables[12]);
unset($earth, $moon, $stars);

If a variable is present in the query string of a URL, even if it has no value assigned to it, it is set. Thus:

http://www.example.com/set.php?chimps=&monkeys=12

sets $_GET['monkeys'] to 12 and $_GET['chimps'] to the empty string.

All unset variables are also empty. Set variables may be empty or nonempty. Empty variables have values that evaluate to false as a boolean: the integer 0, the double 0.0, the empty string, the string "0", the boolean false, an array with no elements, an object with no variables or methods, and NULL. Everything else is nonempty. This includes the string "00", and the string " ", containing just a space character.

Variables evaluate to either true or false. The values listed earlier that evaluate to false as a boolean are the complete set of what's false in PHP. Every other value is true. The distinction between empty and false is that emptiness is only possible for variables. Constants and return values from functions can be false, but they can't be empty. For example, the following is valid because $first_name is a variable:

if (empty($first_name)) { .. }

On the other hand, these two examples return parse errors because 0 (a constant) and the return value from get_first_name( ) can't be empty:

if (empty(0)) { .. }
if (empty(get_first_name())) { .. }

Avoiding == Versus = Confusion

Problem

You don't want to accidentally assign values when comparing a variable and a constant.

Solution

Use:

if (12 == $dwarves) { ... }

instead of:

if ($dwarves == 12) { ... }

Putting the constant on the left triggers a parse error with the assignment operator. In other words, PHP complains when you write:

if (12 = $dwarves) { ... }

but:

if ($dwarves = 12) { ... }

silently executes, assigning 12 to the variable $dwarves, and then executing the code inside the block. ($dwarves = 12 evaluates to 12, which is true.)

Discussion

Putting a constant on the left side of a comparison coerces the comparison to the type of the constant. This causes problems when you are comparing an integer with a variable that could be an integer or a string. 0 == $dwarves is true when $dwarves is 0, but it's also true when $dwarves is sleepy. Since an integer (0) is on the left side of the comparison, PHP converts what's on the right (the string sleepy) to an integer (0) before comparing. To avoid this, use the identity operator, 0 === $dwarves, instead.

See Also

Documentation for = at http://www.php.net/language.operators.assignment.php and for == and === at http://www.php.net/manual/language.operators.comparison.php.

Establishing a Default Value

Problem

You want to assign a default value to a variable that doesn't already have a value. It often happens that you want a hardcoded default value for a variable that can be overridden from form input or through an environment variable.

Solution

Use isset( ) to assign a default to a variable that may already have a value:

if (! isset($cars)) { $cars = $default_cars; }

Use the ternary (a ? b : c) operator to give a new variable a (possibly default) value:

$cars = isset($_REQUEST['cars']) ? $_REQUEST['cars'] : $default_cars;

Discussion

Using isset( ) is essential when assigning default values. Without it, the nondefault value can't be 0 or anything else that evaluates to false. Consider this assignment:

$cars = $_REQUEST['cars'] ? $_REQUEST['cars'] : $default_cars;

If $_REQUEST['cars'] is 0, $cars is set to $default_cars even though 0 may be a valid value for $cars.

You can use an array of defaults to set multiple default values easily. The keys in the defaults array are variable names, and the values in the array are the defaults for each variable:

$defaults = array('emperors'  => array('Rudolf II','Caligula'),
                  'vegetable' => 'celery',
                  'acres'     => 15);

foreach ($defaults as $k => $v) {
    if (! isset($GLOBALS[$k])) { $GLOBALS[$k] = $v; }
}

Because the variables are set in the global namespace, the previous code doesn't work for setting function-private defaults. To do that, use variable variables:

foreach ($defaults as $k => $v) {
    if (! isset($$k)) { $$k = $v; }
}

See Also

Documentation on isset( ) at http://www.php.net/isset; variable variables are discussed in Recipe 5.5 and at http://www.php.net/language.variables.variable.

Exchanging Values Without Using Temporary Variables

Problem

You want to exchange the values in two variables without using additional variables for storage.

Solution

To swap $a and $b:

list($a,$b) = array($b,$a);

Discussion

PHP's list( ) language construct lets you assign values from an array to individual variables. Its counterpart on the right side of the expression, array( ) , lets you construct arrays from individual values. Assigning the array that array( ) returns to the variables in the list( ) lets you juggle the order of those values. This works with more than two values, as well:

list($yesterday,$today,$tomorrow) = array($today,$tomorrow,$yesterday);

This method isn't faster than using temporary variables, so you should use it for clarity, but not speed.

See Also

Documentation on list( ) at http://www.php.net/list and array( ) at http://www.php.net/array.

Creating a Dynamic Variable Name

Problem

You want to construct a variable's name dynamically. For example, you want to use variable names that match the field names from a database query.

Solution

Use PHP's variable variable syntax by prepending a $ to a variable whose value is the variable name you want:

$animal = 'turtles';
$turtles = 103;
print $$animal;
103
            

Discussion

The previous example prints 103. Because $animal = 'turtles', $$animal is $turtles, which equals 103.

Using curly braces, you can construct more complicated expressions that indicate variable names:

$stooges = array('Moe','Larry','Curly');
$stooge_moe = 'Moses Horwitz';
$stooge_larry = 'Louis Feinberg';
$stooge_curly = 'Jerome Horwitz';

foreach ($stooges as $s) {
  print "$s's real name was ${'stooge_'.strtolower($s)}.\n";
}
Moe's real name was Moses Horwitz.
               Larry's real name was Louis Feinberg.
               Curly's real name was Jerome Horwitz.
            

PHP evaluates the expression between the curly braces and uses it as a variable name. That expression can even have function calls in it, such as strtolower( ).

Variable variables are also useful when iterating through similarly named variables. Say you are querying a database table that has fields named title_1, title_2, etc. If you want to check if a title matches any of those values, the easiest way is to loop through them like this:

for ($i = 1; $i <= $n; $i++) {
    $t = "title_$i";
    if ($title == $$t) { /* match */ }
}

Of course, it would be more straightforward to store these values in an array, but if you are maintaining old code that uses this technique (and you can't change it), variable variables are helpful.

The curly brace syntax is also necessary in resolving ambiguity about array elements. The variable variable $$donkeys[12] could have two meanings. The first is "take what's in the 12th element of the $donkeys array and use that as a variable name." Write this as: ${$donkeys[12]}. The second is, "use what's in the scalar $donkeys as an array name and look in the 12th element of that array." Write this as: ${$donkeys}[12].

See Also

http://www.php.net/language.variables.variable for documentation on variable variables.

Using Static Variables

Problem

You want a local variable to retain its value between invocations of a function.

Solution

Declare the variable as static:

function track_times_called( ) {
    static $i = 0;
    $i++;
    return $i;
}

Discussion

Declaring a variable static causes its value to be remembered by a function. So, if there are subsequent calls to the function, you can access the value of the saved variable. The pc_check_the_count( ) function shown in Example 5-1 uses static variables to keep track of the strikes and balls for a baseball batter.

Example 5-1. pc_check_the_count( )

function pc_check_the_count($pitch) {
    static $strikes = 0;
    static $balls   = 0;

    switch ($pitch) {
    case 'foul':
        if (2 == $strikes) break; // nothing happens if 2 strikes
        // otherwise, act like a strike
    case 'strike':
        $strikes++;
        break;
    case 'ball':
        $balls++;
        break;
    }

    if (3 == $strikes) {
        $strikes = $balls = 0;
        return 'strike out';
    }
    if (4 == $balls) {
        $strikes = $balls = 0;
        return 'walk';
    }
    return 'at bat';
}

$what_happened = check_the_count($pitch);

In pc_check_the_count( ), the logic of what happens to the batter depending on the pitch count is in the switch statement inside the function. You can instead return the number of strikes and balls, but this requires you to place the checks for striking out, walking, and staying at the plate in multiple places in the code.

While static variables retain their values between function calls, they do so only during one invocation of a script. A static variable accessed in one request doesn't keep its value for the next request to the same page.

See Also

Documentation on static variables at http://www.php.net/language.variables.scope.

Sharing Variables Between Processes

Problem

You want a way to share information between processes that provides fast access to the shared data.

Solution

Store the data in a shared memory segment, and guarantee exclusive access to the shared memory with a semaphore:

$semaphore_id = 100;
$segment_id   = 200;
// get a handle to the semaphore associated with the shared memory
// segment we want
$sem = sem_get($semaphore_id,1,0600);
// ensure exclusive access to the semaphore
sem_acquire($sem) or die("Can't acquire semaphore");
// get a handle to our shared memory segment
$shm = shm_attach($segment_id,16384,0600);
// retrieve a value from the shared memory segment
$population = shm_get_var($shm,'population');
// manipulate the value
$population += ($births + $immigrants - $deaths - $emigrants);
// store the value back in the shared memory segment
shm_put_var($shm,'population',$population);
// release the handle to the shared memory segment
shm_detach($shm);
// release the semaphore so other processes can acquire it
sem_release($sem);

Discussion

A shared memory segment is a slice of your machine's RAM that different processes (such as the multiple web server processes that handle requests) can access. A semaphore makes sure that the different processes don't step on each other's toes when they access the shared memory segment. Before a process can use the segment, it needs to get control of the semaphore. When it's done with the segment, it releases the semaphore for another process to grab.

To get control of a semaphore, use sem_get( ) to find the semaphore's ID. The first argument to sem_get( ) is an integer semaphore key. You can make the key any integer you want, as long as all programs that need to access this particular semaphore use the same key. If a semaphore with the specified key doesn't already exist, it's created, the maximum number of processes that can access the semaphore is set to the second argument of sem_get( ) (in this case, 1), and the semaphore's permissions are set to sem_get( )'s third argument (0600). These permissions work just like file permissions, so 0600 means that the user that created the semaphore can read it and write to it. In this context, user doesn't just mean the process that created the semaphore but any process with the same user ID. Permissions of 0600 should be appropriate for most uses, in which web server processes run as the same user.

sem_get( ) returns an identifier that points to the underlying system semaphore. Use this ID to gain control of the semaphore with sem_acquire( ) . This function waits until the semaphore can be acquired (perhaps waiting until other processes release the semaphore) and then returns true. It returns false on error. Errors include invalid permissions or not enough memory to create the semaphore. Once the semaphore is acquired, you can read from the shared memory segment.

First, establish a link to the particular shared memory segment with shm_attach( ) . As with sem_get( ), the first argument to shm_attach( ) is an integer key. This time, however it identifies the desired segment, not the semaphore. If the segment with the specified key doesn't exist, the other arguments create it. The second argument (16384) is the size in bytes of the segment, and the last argument (0600) are the permissions on the segment. shm_attach(200,16384,0600) creates a 16K shared memory segment that can be read from and written to only by the user who created it. The function returns the identifier you need to read from and write to the shared memory segment.

After attaching to the segment, pull variables out of it with shm_get_var($shm, 'population') . This looks in the shared memory segment identified by $shm and retrieves the value of the variable called population. You can store any type of variable in shared memory. Once the variable is retrieved, it can be operated on like other variables. shm_put_var($shm,'population',$population) puts the value of $population back into the shared memory segment as a variable called population.

You're now done with the shared memory statement. Detach from it with shm_detach( ) and release the semaphore with sem_release( ) so another process can use it.

Shared memory's chief advantage is that it's fast. But since it's stored in RAM, it can't hold too much data, and it doesn't persist when a machine is rebooted (unless you take special steps to write the information in shared memory to disk before shutdown and then load it into memory again at startup). Also, shared memory is not available on Windows.

See Also

Recipe 8.28 includes a program that uses shared memory; documentation on shared memory and semaphore functions at http://www.php.net/sem.

Encapsulating Complex Data Types as a String

Problem

You want a string representation of an array or object for storage in a file or database. This string should be easily reconstitutable into the original array or object.

Solution

Use serialize( ) to encode variables and their values into a textual form:

$pantry = array('sugar' => '2 lbs.','butter' => '3 sticks');
$fp = fopen('/tmp/pantry','w') or die ("Can't open pantry");
fputs($fp,serialize($pantry));
fclose($fp);

To recreate the variables, use unserialize( ) :

$new_pantry = unserialize(join('',file('/tmp/pantry')));

Discussion

The serialized string that is reconstituted into $pantry looks like:

a:2:{s:5:"sugar";s:6:"2 lbs.";s:6:"butter";s:8:"3 sticks";}

This stores enough information to bring back all the values in the array, but the variable name itself isn't stored in the serialized representation.

When passing serialized data from page to page in a URL, call urlencode( ) on the data to make sure URL metacharacters are escaped in it:

$shopping_cart = array('Poppy Seed Bagel' => 2,
                       'Plain Bagel' => 1,
                       'Lox' => 4);
print '<a href="next.php?cart='.urlencode(serialize($shopping_cart)).'">Next</a>';

The magic_quotes_gpc and magic_quotes_runtime configuration settings affect data being passed to unserialize( ). If magic_quotes_gpc is on, data passed in URLs, POST variables, or cookies must be processed with stripslashes( ) before it's unserialized:

$new_cart = unserialize(stripslashes($cart)); // if magic_quotes_gpc is on
$new_cart = unserialize($cart);               // if magic_quotes_gpc is off

If magic_quotes_runtime is on, serialized data stored in a file must be processed with addslashes( ) when writing and stripslashes() when reading:

$fp = fopen('/tmp/cart,'w');
fputs($fp,addslashes(serialize($a)));
fclose($fp);

// if magic_quotes_runtime is on
$new_cart = unserialize(stripslashes(join('',file('/tmp/cart'))));
// if magic_quotes_runtime is off
$new_cart = unserialize(join('',file('/tmp/cart')));

Serialized data read from a database must also be processed with stripslashes( ) when magic_quotes_runtime is on:

mysql_query(
    "INSERT INTO cart (id,data) VALUES (1,'".addslashes(serialize($cart))."')");

$r = mysql_query('SELECT data FROM cart WHERE id = 1');
$ob = mysql_fetch_object($r);
// if magic_quotes_runtime is on
$new_cart = unserialize(stripslashes($ob->data));
// if magic_quotes_runtime is off
$new_cart = unserialize($ob->data);

Serialized data going into a database always needs to have addslashes( ) called on it (or another database-appropriate escaping method) to ensure it's saved properly.

See Also

Recipe 10.8 for information on escaping data for a database.

Dumping Variable Contents as Strings

Problem

You want to inspect the values stored in a variable. It may be a complicated nested array or object, so you can't just print it out or loop through it.

Solution

Use print_r( ) or var_dump( ):

$array = array("name" => "frank", 12, array(3, 4));

print_r($array);
Array
               (
                   [name] => frank
                   [0] => 12
                   [1] => Array
                       (
                           [0] => 3
                           [1] => 4
                       )
               )
var_dump($array);
array(3) {
                 ["name"]=>
                 string(5) "frank"
                 [0]=>
                 int(12)
                 [1]=>
                 array(2) {
                   [0]=>
                   int(3)
                   [1]=>
                   int(4)
                 }
               }
            

Discussion

The output of print_r( ) is more concise and easier to read. The output of var_dump( ), however, gives data types and lengths for each variable.

Since these functions recursively work their way through variables, if you have references within a variable pointing back to the variable itself, you can end up with an infinite loop. Both functions stop themselves from printing variable information forever, though. Once print_r( ) has seen a variable once, it prints *RECURSION* instead of printing information about the variable again and continues iterating through the rest of the information it has to print. When var_dump( ) sees a variable more than three times, it throws a fatal error and ends script execution. Consider the arrays $user_1 and $user_2, which reference each other through their friend elements:

$user_1 = array('name' => 'Max Bialystock',
                'username' => 'max');

$user_2 = array('name' => 'Leo Bloom',
                'username' => 'leo');

// Max and Leo are friends
$user_2['friend'] = &$user_1;
$user_1['friend'] = &$user_2;

// Max and Leo have jobs
$user_1['job'] = 'Swindler';
$user_2['job'] = 'Accountant';

The output of print_r($user_2) is:

Array
(
    [name] => Leo Bloom
    [username] => leo
    [friend] => Array
        (
            [name] => Max Bialystock
            [username] => max
            [friend] => Array
                (
                    [name] => Leo Bloom
                    [username] => leo
                    [friend] => Array
 *RECURSION*
                    [job] => Accountant
                )

            [job] => Swindler
        )

    [job] => Accountant
)

When print_r( ) sees the reference to $user_1 the second time, it prints *RECURSION* instead of descending into the array. It then continues on its way, printing the remaining elements of $user_1 and $user_2.

Confronted with recursion, var_dump( ) behaves differently:

array(4) {
  ["name"]=>
  string(9) "Leo Bloom"
  ["username"]=>
  string(3) "leo"
  ["friend"]=>
  &array(4) {
    ["name"]=>
    string(14) "Max Bialystock"
    ["username"]=>
    string(3) "max"
    ["friend"]=>
    &array(4) {
      ["name"]=>
      string(9) "Leo Bloom"
      ["username"]=>
      string(3) "leo"
      ["friend"]=>
      &array(4) {
        ["name"]=>
        string(14) "Max Bialystock"
        ["username"]=>
        string(3) "max"
        ["friend"]=>
        &array(4) {
          ["name"]=>
          string(9) "Leo Bloom"
          ["username"]=>
          string(3) "leo"
          ["friend"]=>
          &array(4) {
            ["name"]=>
            string(14) "Max Bialystock"
            ["username"]=>
            string(3) "max"
            ["friend"]=>
            &array(4) {
              ["name"]=>
              string(9) "Leo Bloom"
              ["username"]=>
              string(3) "leo"
              ["friend"]=>
              &array(4) {
<br />
<b>Fatal error</b>:  Nesting level too deep - recursive dependency? in 
<b>var-dump.php</b> on line <b>15</b><br />

It's not until the fourth appearance of the reference to $user_1 that var_dump( ) stops recursing. When it does, it throws a fatal error, and no more variable dumping (or script execution) occurs.

Even though print_r( ) and var_dump( ) print their results instead of returning them, you can capture the data without printing it using output buffering:

ob_start();
var_dump($user);
$dump = ob_get_contents();
ob_end_clean();

This puts the results of var_dump($user) in $dump.

See Also

Output buffering is discussed in Recipe 8.13; error handling with PEAR's DB module, shown in Recipe 10.9, uses output buffering with print_r( ) to save error messages; documentation on print_r( ) at http://www.php.net/print-r and var_dump( ) at http://www.php.net/var-dump .

Personal tools