5.9. Dumping Variable Contents as Strings5.9.1. ProblemYou 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. 5.9.2. SolutionUse print_r( ) or var_dump( ):
5.9.3. DiscussionThe 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:
The output of print_r($user_2) is:
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:
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. 5.9.4. See AlsoOutput 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 .
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|