alecks Posted April 12, 2008 Share Posted April 12, 2008 Is there an easy way to turn an associative array into an object? Something like (within the object) : $this = (object) array('bleh'=>'teh'); The above does not work... Link to comment https://forums.phpfreaks.com/topic/100809-associative-array-to-object/ Share on other sites More sharing options...
Daniel0 Posted April 12, 2008 Share Posted April 12, 2008 It does work... <?php $var = (object) array('bleh' => 'teh'); var_dump($var); ?> object(stdClass)#1 (1) { ["bleh"]=> string(3) "teh" } Link to comment https://forums.phpfreaks.com/topic/100809-associative-array-to-object/#findComment-515539 Share on other sites More sharing options...
alecks Posted April 12, 2008 Author Share Posted April 12, 2008 That does work; the context I was trying to implement it was within the object instantiation. I wanted to fetch data from a database and then change the array into object vars. Ex: <?php class obj{ function obj($name) { $data = <fetch from database> $this = (object) $data; } } $obj = new obj('name'); ?> Link to comment https://forums.phpfreaks.com/topic/100809-associative-array-to-object/#findComment-515543 Share on other sites More sharing options...
Daniel0 Posted April 12, 2008 Share Posted April 12, 2008 You cannot redefine $this... Just loop through the results and set it manually. Link to comment https://forums.phpfreaks.com/topic/100809-associative-array-to-object/#findComment-515544 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.