thomas-peter
thomas-peter

Reputation: 7944

How do I easily access strangely name members of an object?

Simply consider this...

<?php

$phoo = json_decode( '{ "a-b": 2 }');

// causes "PHP Fatal error:  Cannot use object of type stdClass as array";
echo $phoo['a-b'];

// causes PHP Notice:  Use of undefined constant b - assumed 'b'
echo $phoo->a-b;

Aside from using something like get_object_vars() or (array) to convert it, is there any way to access the value at 'a-b'?

Upvotes: 0

Views: 28

Answers (2)

Mahendra Jella
Mahendra Jella

Reputation: 5596

It's because of the hyphen, which implies substraction.

Try

 $photo->{'a-b'}

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212412

To prevent the - being treated as a minus operator, and trying to subtract a constant value named b from property $phoo->a, you need to do

echo $phoo->{'a-b'};

Upvotes: 2

Related Questions