8

I need an escape sequence for - or the minus sign for php. The object has a name-value pair where the name happens to be having - between 2 words.

I can't do this using \ the standard escape sequence (- isn't anyways documented).

I can store the name in a $myvariable which can be used but out of curiosity is it possible to do the following?

$myobject->myweird-name

This gives an Error because of -

Salman A
  • 248,760
  • 80
  • 417
  • 510
umesh moghariya
  • 165
  • 2
  • 8

2 Answers2

39

This is what you need:

$myobject->{'myweird-name'};
MichaelRushton
  • 10,628
  • 4
  • 43
  • 63
9

If you need to look up an index, there are a couple of ways of doing it:

// 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'];

If you need to work within a string (which is not your best idea, you should be using manual concatenation where possible as it is faster and parsed strings is unnecessary), then you should use {} to basically escape the entire sequence:

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

Since you mentioned that this is LinkedIn's API which, I believe, has the option of returning XML, it might be faster (and possibly cleaner/clearer) to use the XML method calls and not use the objects themselves. Food for thought.

cwallenpoole
  • 76,131
  • 26
  • 124
  • 163