I have an object as this:
object(stdClass)#27 (1)
{
[0] => object(stdClass)#26 (6)
{
["_id"] => object(MongoId)#24 (1)
{
["$id"] => string(24) "4e6ea439caa47c2c0c000000"
}
["username"] => string(16) "wdfkewkghbrjkghb"
["email"]=> string(24) "wdhbfjkwhegerg@€rg.efg"
["password"]=> string(32) "4297f44b13955235245b2497399d7a93"
["slug"]=> string(16) "wdfkewkghbrjkghb"
["insert_datetime"]=> string(19) "2011-09-13 12:09:49"
}
}
I assign this object to $user.
I can’t get access on this object properties doing $user->username cause I receive the message:
Undefined property:
stdClass::$username
Then if I do var_dump(get_object_vars($user)) it returns an empty array.
How do I grab the properties? I don’t want to use loops if I can avoid it.
The process is this:
-
Retrieve results from mongo_db:
$returns = array(); while ($documents->hasNext()) { if ($this->CI->config->item('mongo_return') == 'object') { $returns[] = (object) $documents->getNext(); } if ($this->CI->config->item('mongo_return') == 'array') { $returns[] = (array) $documents->getNext(); } } if ($this->CI->config->item('mongo_return') == 'object') { return (object)$returns; } if ($this->CI->config->item('mongo_return') == 'array') { return $returns; } -
passing data to model
function populateBy($what = false) { return $this->mongo_db ->where($what) ->get($this->tb['users']); } -
definitely grab results in controller:
$what = array( 'email'=>$email, 'password'=>$password, 'confirm'=>'1' ); $user = $this->model_user->populateBy($what);
As gilden says, the property you’re looking for is a property of a subobject. However, he missed that object property access is not the same as array element access.
The real problem you’re facing here is that you’ve converted an array to object, and now you have a numeric property name. To get to properties you have to use syntax like
$user->0->username, but clearly this is not valid as0is not a valid variable name.From the documentation:
The function
get_object_varsconverts back into an array again so that it appears to work, but in fact anything could happen: the behaviour is unspecified because the object elements were rendered inaccessible in the intermediate stage. Similarly,$user->{'0'}->usernamemay work for you but I would avoid it.Unfortunately this means that you’ll have to change the way your code works: do not convert a numerically-indexed array to an object.