1

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.

zPuls3
  • 330
  • 3
  • 13
  • Why do you want to access them? it seems as wrong way – splash58 Feb 01 '22 at 11:42
  • 1
    Please learn the code you use. https://plugins.trac.wordpress.org/browser/motopress-hotel-booking-lite/trunk/includes/entities/room-type.php here you can see a getter for every property. – u_mulder Feb 01 '22 at 11:45
  • @splash58 This is on a wordpress plugin. The main reason that I am asking is if you can tell what is the reason that this is happening – zPuls3 Feb 01 '22 at 11:52

1 Answers1

1

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

BacLuc
  • 93
  • 1
  • 4