note 78851 added to function.print-r

From: Date: Wed, 31 Oct 2007 00:27:06 +0000
Subject: note 78851 added to function.print-r
Groups: php.notes 
Request: Send a blank email to php-notes+get-131838@lists.php.net to get a copy of this message
Here's a PHP version of print_r which can be tailored to your needs. Shows protected and private properties of objects and detects recursion (for objects only!). Usage: void u_print_r ( mixed $expression [, array $ignore] ) Use the $ignore parameter to provide an array of property names that shouldn't be followed recursively. <?php function u_print_r($subject, $ignore = array(), $depth = 1, $refChain = array()) { if ($depth > 20) return; if (is_object($subject)) { foreach ($refChain as $refVal) if ($refVal === $subject) { echo "*RECURSION*\n"; return; } array_push($refChain, $subject); echo get_class($subject) . " Object ( \n"; $subject = (array) $subject; foreach ($subject as $key => $val) if (is_array($ignore) && !in_array($key, $ignore, 1)) { echo str_repeat(" ", $depth * 4) . '['; if ($key{0} == "\0") { $keyParts = explode("\0", $key); echo $keyParts[2] . (($keyParts[1] == '*') ? ':protected' : ':private'); } else echo $key; echo '] => '; u_print_r($val, $ignore, $depth + 1, $refChain); } echo str_repeat(" ", ($depth - 1) * 4) . ")\n"; array_pop($refChain); } elseif (is_array($subject)) { echo "Array ( \n"; foreach ($subject as $key => $val) if (is_array($ignore) && !in_array($key, $ignore, 1)) { echo str_repeat(" ", $depth * 4) . '[' . $key . '] => '; u_print_r($val, $ignore, $depth + 1, $refChain); } echo str_repeat(" ", ($depth - 1) * 4) . ")\n"; } else echo $subject . "\n"; } ?> Example: <?php class test { public $var1 = 'a'; protected $var2 = 'b'; private $var3 = 'c'; protected $array = array('x', 'y', 'z'); } $test = new test(); $test->recursiveRef = $test; $test->anotherRecursiveRef->recursiveRef = $test; $test->dont->follow = 'me'; u_print_r($test, array('dont')); ?> Will produce: test Object ( [var1] => a [var2:protected] => b [var3:private] => c [array:protected] => Array ( [0] => x [1] => y [2] => z ) [recursiveRef] => *RECURSION* [anotherRecursiveRef] => stdClass Object ( [recursiveRef] => *RECURSION* ) ) ---- Server IP: 213.249.64.162 Probable Submitter: 194.109.253.196 ---- Manual Page -- http://www.php.net/manual/en/function.print-r.php Edit -- https://master.php.net/note/edit/78851 Del: integrated -- https://master.php.net/note/delete/78851/integrated Del: useless -- https://master.php.net/note/delete/78851/useless Del: bad code -- https://master.php.net/note/delete/78851/bad+code Del: spam -- https://master.php.net/note/delete/78851/spam Del: non-english -- https://master.php.net/note/delete/78851/non-english Del: in docs -- https://master.php.net/note/delete/78851/in+docs Del: other reasons-- https://master.php.net/note/delete/78851 Reject -- https://master.php.net/note/reject/78851 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#131838) next »