How to access an object when the property name contains - (hyphen)

I need escape sequence for -or minus sign for php. An object has a pair of names and values, where the name has -between two words.

I cannot do this using a \standard escape sequence ( -not documented).

I can save the name in $myvariable, which can be used, but out of curiosity you can do the following:

$myobject->myweird-name

This gives an error due to -

+5
source share
2 answers

This is what you need:

$myobject->{'myweird-name'};
+30
source

If you need to find an index, there are several ways to do this:

// use a variable
$prop = 'my-crazy-property';
$obj->$prop;

// use {}
$obj->{'my-crazy-property'};

// get_object_vars (better with a lot of crazy properties)
$vars = get_object_vars($obj);
$vars['my-crazy-property'];

// you can cast to an array directly
$arr = (array)$obj;
$arr['my-crazy-property'];

( , , , ), {},

$foo = new stdClass();
$foo->{"my-crazy-property"} = 1;
var_dump("my crazy property is {$foo->{"my-crazy-property"}}";

, LinkedIn API, , , XML, (, , /) XML . .

+6

All Articles