Php’s print_r for as3

Here is really useful class tools for as3 based on php function found on http://dev.base86.com website.

Exemple use :

import com.base86.Tools;
 
var obj:Array = new Array();
obj['a'] = { one: 1, two: 2, three: 3 };
obj['b'] = [ 'one', 'two', [ 'three' ] ];
obj['c'] = new MovieClip();
 
Tools.pr(obj);

The console will display:

(array) {
	[a] => (object) {
		[two] => (number) 2
		[three] => (number) 3
		[one] => (number) 1
	}
	[b] => (array) {
		[0] => (string) one
		[1] => (string) two
		[2] => (array) {
			[0] => (string) three
		}
	}
	[c] => (object) [object MovieClip]
}

And the class now :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.base86 {
	public class Tools {
		/**
		 * An equivalent of PHP's recursive print function print_r, which displays objects and arrays in a way that's readable by humans
		 * @param obj    Object to be printed
		 * @param level  (Optional) Current recursivity level, used for recursive calls
		 * @param output (Optional) The output, used for recursive calls
		 */
		public static function pr(obj:*, level:int = 0, output:String = ''):* {
			if(level == 0) output = '('+ Tools.typeOf(obj) +') {\n';
			else if(level == 10) return output;
 
			var tabs:String = '\t';
			for(var i:int = 0; i < level; i++, tabs += '\t') { }
			for(var child:* in obj) {
				output += tabs +'['+ child +'] => ('+  Tools.typeOf(obj[child]) +') ';
 
				if(Tools.count(obj[child]) == 0) output += obj[child];
 
				var childOutput:String = '';
				if(typeof obj[child] != 'xml') {
					childOutput = Tools.pr(obj[child], level + 1);
				}
				if(childOutput != '') {
					output += '{\n'+ childOutput + tabs +'}';
				}
				output += '\n';
			}
 
			if(level == 0) trace(output +'}\n');
			else return output;
		}
 
		/**
		 * An extended version of the 'typeof' function
		 * @param 	variable
		 * @return	Returns the type of the variable
		 */
		public static function typeOf(variable:*):String {
			if(variable is Array) return 'array';
			else if(variable is Date) return 'date';
			else return typeof variable;
		}
 
		/**
		 * Returns the size of an object
		 * @param obj Object to be counted
		 */
		public static function count(obj:Object):uint {
			if(Tools.typeOf(obj) == 'array') return obj.length;
			else {
				var len:uint = 0;
				for(var item:* in obj) {
					if(item != 'mx_internal_uid') len++;
				}
				return len;
			}
		}
	}
}

1 thought on “Php’s print_r for as3

Leave a Reply

Your email address will not be published. Required fields are marked *