Object extract properties - php

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 as 0 is not a valid variable name.
From the documentation:
If an object is converted to an array, the result is an array whose
elements are the object's properties. The keys are the member variable
names, with a few notable exceptions: integer properties are
unaccessible [sic]; private variables have the class name prepended to the
variable name; protected variables have a '*' prepended to the
variable name. These prepended values have null bytes on either side.
This can result in some unexpected behaviour:
The function get_object_vars converts 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'}->username may 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.

Your username property is not where you're looking for it. Try
$username = $user[0]->username;
EDIT Trying this gives me some unexpected results. I get "Cannot use object of type stdClass as array" so what I think you should do is using a foreach loop
// $users is the object in this sample
foreach($users as $user)
{
$username = $user->username;
}
EDIT 2 You could use get_object_vars
$users = get_object_vars($users);
$username = $users[0]->username;

Related

PHP array cannot get value from key

I got an object that has some private properties that i cannot access.
var_dump($roomType);
// I deleted some of the results of var_dump
object(MPHB\Entities\RoomType)#2003 (6) {
["id":"MPHB\Entities\RoomType":private]=> int(15)
["originalId":"MPHB\Entities\RoomType":private]=> int(15)
["description":"MPHB\Entities\RoomType":private]=> string(0) ""
["excerpt":"MPHB\Entities\RoomType":private]=> string(0) ""
["imageId":"MPHB\Entities\RoomType":private]=> int(406)
["status":"MPHB\Entities\RoomType":private]=> string(7) "publish" }
So I convert the object to array.
$array = (array) $roomType;
print_r($array);
/*
Array (
[MPHB\Entities\RoomTypeid] => 15
[MPHB\Entities\RoomTypeoriginalId] => 15
[MPHB\Entities\RoomTypedescription] =>
[MPHB\Entities\RoomTypeexcerpt] =>
[MPHB\Entities\RoomTypeimageId] => 406
[MPHB\Entities\RoomTypestatus] => publish )
*/
but I still cannot access the values from key like this
var_dump($array["MPHB\Entities\RoomTypeimageId"]); // NULL
The only workaround i got is this :
$array = (array) $roomType;
$array_keys = array_keys($array);
$array_key_id = $array_keys[4];
echo $array[$array_key_id]; // 406
But I am not sure that the key is at the same position all the time, so I want to find an other way.
I escaped the slashes but still the same, any ideas?
Edit :
So I tried to compare the $array_key_id (which is MPHB\Entities\RoomTypeimageId) with the same value (copied from the browser) and it fails.
So I did a loop and pushed the key=>value to the existing $array and now I can get the value.
There must be something like null bytes as BacLuc said.
I would guess that escaping is the problem:
$array["MPHB\Entities\RoomTypeimageId"] -> $array["MPHBEntitiesRoomTypeimageId"] for which there is no value in the array.
But $array["MPHB\\Entities\\RoomTypeimageId"] might work.
Edit:
it's escaping plus on private properties have the class name prepended to the property name, surrounded with null bytes.
Test is here: http://sandbox.onlinephpfunctions.com/code/d218d41f22e86dd861f562de9c040febb011d577
From:
Convert a PHP object to an associative array
https://www.php.net/manual/en/language.types.array.php#language.types.array.casting

PHP Array to Object

Given the following array:
$array = array(
'item_1' => array(
'item_1_1' => array(
'item_1_1_1' => 'Hello',
),
'item_1_2' => 'World',
),
'item_2' => array(),
);
How can I convert that into an Object?
Option 1
$obj = (object) $array;
Or
Option 2
$object = json_decode(json_encode($array), FALSE);
Or something else?
I would like to know the difference in the output between the 2 option and understand the best practice for creating this conversion.
Well you are answering somehow your own question, but if you want to have an object with the attributes like your array you have to cast it, this way an array will remain an array
$obj = (object) $array;
OUTPUT:
object(stdClass)#1 (2) {
["item_1"]=>
array(2) {
["item_1_1"]=>
array(1) {
["item_1_1_1"]=>
string(5) "Hello"
}
["item_1_2"]=>
string(5) "World"
}
["item_2"]=>
array(0) {
}
}
if you are using the json_decode version it will convert arrays to objects too:
object(stdClass)#2 (2) {
["item_1"]=>
object(stdClass)#3 (2) {
["item_1_1"]=>
object(stdClass)#4 (1) {
["item_1_1_1"]=>
string(5) "Hello"
}
["item_1_2"]=>
string(5) "World"
}
["item_2"]=>
array(0) {
}
}
NOTE: just the empty array will be an array here.
To Answer your question: The best practice depends on what YOU need.
It depends, really: if you are working on data that might be an array in one case, and an object the next, it would probably be best to use the json_decode trick, simply because unlike a cast, its result is "recursive". There is one very important thing to keep in mind here, though: numeric indexes can, and probably will cause problems for you at some point in time. Take a look at this bug report
This is documented here, but not in a way that really stands out:
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible;
Exampe of the problem:
$data = [
'foo' => 'bar',
123 => 'all is well',
];
$obj = json_decode(json_encode($data));
var_dump($obj->foo);//bar
var_dump($obj->{123});//all is well
$cast = (array) $obj;
var_dump($cast);//shows both keys
var_dump(isset($cast[123]));//FALSE!!!
var_dump(isset($cast['123']));//FALSE
Basically: If you start converting arrays to objects and back again, numeric keys are not reliable anymore. If I were you, I'd simply change the code that is passing the data where possible, or I'd create a value object that can be set using an array or an object, and normalize the data that way.

PHP - Access value from previously-defined key during array initialization

I'm looking to see if it's possible to access the value of a key I previously defined within the same array.
Something like:
$test = array(
'foo' => 1,
'bar' => $test['foo']
);
I know I can always do so after initialization, I am just wondering if it's possible during initialization?
No, $test doesn't exist until the full constructor is evaluated.
For example: http://codepad.viper-7.com/naUprJ
Notice: Undefined variable: test..
array(2) { ["foo"]=> int(1) ["bar"]=> NULL }
It's probably for the best. Imagine of this worked:
$test = array('foo' => $test['foo']); // mwahaha
If you need to do this a lot, you could create a class that takes keys of a particular format that flag to the class constructor that it should be parsed until all relevant keys are evaluated.

PHP Object () identifier

What is the name of the integer between brackets in a var_dump of an object. And how do I acces it with PHP?
I'm referring to the (3) in the next example.
object(SimpleXMLElement)#18 (3) {
["ID"]=>
string(3) "xx"
["Name"]=>
string(25) "xx"
["Date"]=>
string(10) "xx"
}
this is the number of properties of an object. to count this, you can cast your object to an array and use count():
$number = count((array)$object);
EDIT: i did a small test (see at codepad) wich prooves that casting to an array is what you want to do instead of using get_object_vars() as others mentioned because the later one doesn't count private properties while array-casting as well as var_dump do count these.
It's the number of public properties of that object, and isn't directly accessible
What is the name of the integer between brackets in a var_dump of an object. And how do I acces it with PHP?
I'm referring to the (3) in the next example.
That's the number of public members it has (namely, ID, Name and Date). If you want to know that number, you could just use count( get_object_vars( $object ) ):
<?php
$foo = new stdClass;
$foo->foo = 42;
$foo->bar = 42;
$foo->baz = 42;
var_dump( count( get_object_vars( $foo ) ) );

PHP Undefined index of array. Why?

This is... I don't even know what this is happening.
// var_dump of items before
object(stdClass)[84]
public '75' => object(stdClass)[87]
$items = (array) $items; // Casting unserialized stdClass to array
var_dump($items);
//Result of var dump:
array
'75' =>
object(stdClass)[87]
//Now lets get this item:
var_dump($items[75]); // Error
var_dump($items['75']); // Error
What the?
Thanks.
I think, you are using a debug extension, so the var_dump() output is different then standart library, properties can not be numeric but $obj->{'75'} is okay.
If can you reach to the sub object by $items->{'75'} yes you have a numeric property.
otherwise you can try print_r($items); and see the original output, or check the array after get_object_vars()
<?php
$items = new stdClass();
$items->{'75'} = new stdClass();
$items->{'75'}->{'85'} = new stdClass();
$items = (array) $items; // Casting unserialized stdClass to array
$items_array = get_object_vars($items); // getting object vars as an array.
var_dump($items["75"]); // Error
var_dump($items['75']); // Error
var_dump($items_array['75']); // Works
PHP issue : #45959
Read the casting blockquote: http://www.php.net/manual/en/language.types.array.php#language.types.array.casting
Casting to an array doesn't work like that.
See here: get_object_vars() vs. cast to array
and here: http://www.php.net/manual/en/language.types.array.php#language.types.array.casting
Blockquote
"If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.

Categories