How to access object property when property name c

2019-05-02 07:21发布

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 -

标签: php oop syntax
2条回答
虎瘦雄心在
2楼-- · 2019-05-02 07:39

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.

查看更多
戒情不戒烟
3楼-- · 2019-05-02 07:56

This is what you need:

$myobject->{'myweird-name'};
查看更多
登录 后发表回答