note 111930 added to language.types.type-juggling

From: Date: Sat, 13 Apr 2013 15:23:17 +0000
Subject: note 111930 added to language.types.type-juggling
Groups: php.notes 
Request: Send a blank email to php-notes+get-194468@lists.php.net to get a copy of this message
Casting objects to arrays is a pain. Example: <?php class MyClass { private $priv = 'priv_value'; protected $prot = 'prot_value'; public $pub = 'pub_value'; public $MyClasspriv = 'second_pub_value'; } $test = new MyClass(); echo '<pre>'; print_r((array) $test); /* Array ( [MyClasspriv] => priv_value [*prot] => prot_value [pub] => pub_value [MyClasspriv] => second_pub_value ) */ ?> Yes, that looks like an array with two keys with the same name and it looks like the protected field was prepended with an asterisk. But that's not true: <?php foreach ((array) $test as $key => $value) { $len = strlen($key); echo "{$key} ({$len}) => {$value}<br />"; for ($i = 0; $i < $len; ++$i) { echo ord($key[$i]) . ' '; } echo '<hr />'; } /* MyClasspriv (13) => priv_value 0 77 121 67 108 97 115 115 0 112 114 105 118 *prot (7) => prot_value 0 42 0 112 114 111 116 pub (3) => pub_value 112 117 98 MyClasspriv (11) => second_pub_value 77 121 67 108 97 115 115 112 114 105 118 */ ?> The char codes show that the protected keys are prepended with '\0*\0' and private keys are prepended with '\0'.__CLASS__.'\0' so be careful when playing around with this. ---- Server IP: 69.147.83.199 Probable Submitter: 79.114.79.15 ---- Manual Page -- http://php.net/manual/en/language.types.type-juggling.php Edit -- https://master.php.net/note/edit/111930 Del: integrated -- https://master.php.net/note/delete/111930/integrated Del: useless -- https://master.php.net/note/delete/111930/useless Del: bad code -- https://master.php.net/note/delete/111930/bad+code Del: spam -- https://master.php.net/note/delete/111930/spam Del: non-english -- https://master.php.net/note/delete/111930/non-english Del: in docs -- https://master.php.net/note/delete/111930/in+docs Del: other reasons-- https://master.php.net/note/delete/111930 Reject -- https://master.php.net/note/reject/111930 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#194468) next »