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.

3
  • Why do you want to access them? it seems as wrong way Commented Feb 1, 2022 at 11:42
  • 1
    Please learn the code you use. plugins.trac.wordpress.org/browser/motopress-hotel-booking-lite/… here you can see a getter for every property. Commented Feb 1, 2022 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 Commented Feb 1, 2022 at 11:52

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I have tried with \\ or htmlspecialcharacters etc but still nothing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.