note 85440 added to language.types.object

From: Date: Sun, 31 Aug 2008 00:31:18 +0000
Subject: note 85440 added to language.types.object
Groups: php.notes 
Request: Send a blank email to php-notes+get-144019@lists.php.net to get a copy of this message
In response to Harmor and Mithras, you can use the json functions to convert multi-dimensional arrays to objects very reliably. Also, note that just using (object)$x doesn't allow you to access properties inline. For example, this is invalid: <?php $x = array("foo"=>"bar"); echo ((object)$x)->foo; // PHP Parse error, unexpected T_OBJECT_OPERATOR ?> However, this function will let you do that, and will also handle multi-dimensional arrays without any hassle. <?php function to_object ($x) { return (is_object($x) || is_array($x)) ? json_decode(json_encode($x)) : (object) $x; } echo to_object( array("foo"=>"bar") )->foo; // "bar" ?> Note that *numeric* arrays will not be converted to objects using this method. ---- Server IP: 208.69.120.35 Probable Submitter: 98.210.242.47 ---- Manual Page -- http://www.php.net/manual/en/language.types.object.php Edit -- https://master.php.net/note/edit/85440 Del: integrated -- https://master.php.net/note/delete/85440/integrated Del: useless -- https://master.php.net/note/delete/85440/useless Del: bad code -- https://master.php.net/note/delete/85440/bad+code Del: spam -- https://master.php.net/note/delete/85440/spam Del: non-english -- https://master.php.net/note/delete/85440/non-english Del: in docs -- https://master.php.net/note/delete/85440/in+docs Del: other reasons-- https://master.php.net/note/delete/85440 Reject -- https://master.php.net/note/reject/85440 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#144019) next »