Good day.

there is such an object:

$res = object(stdClass)#3 (3) { ["size"]=> "16", ["validator"]=> "", ["validator-error"]=> "не работает", } 

if I write $res->size , I get 16 ,

but if I write $res->validator-error , then I will receive only Notice: Use of undefined constant error - assumed 'error' in ...

How to get validator-error value in this object?

  • $res->{'validator-error'} - Alexey Shimansky
  • thanks, it helped. postpone the comment in response, mark it accepted - Maximmka

3 answers 3

In php there is a complex (curly) syntax, it allows you to use complex expressions. Any scalar variable, an array element, or an object property can be represented in the string by this syntax. You just need to write an expression enclosing it in { and } .

This is most often used in strings. But it is also possible to do it without them.

As an example

 class foo { var $bar = 'I am bar.'; } $foo = new foo(); $bar = 'bar'; $baz = array('foo', 'bar', 'baz', 'quux'); echo "{$foo->$bar}\n"; echo "{$foo->{$baz[1]}}\n"; 

Accordingly, if you do not want to convert your object into an array (which is also possible and not prohibited by the law), but you want to access the field of the object, then you can use this very figure syntax.

In your case it will be like this:

 $res->{'validator-error'} 

    Can so

     ((array)$res)['validator-error'] 

      A valid variable name must begin with a letter or underscore and consist of letters, numbers, and underscores in any quantity.

      A variable in PHP cannot contain the character "-".

      • Maybe it got out of the database or the API passed or something else. It doesn’t necessarily boil down to what is being cooked in php. In general, there is no variable name with a hyphen, so for a second ;-) - Alexey Shimansky
      • @ AlekseyShimansky about that and speech, that it is not a variable, and you should not pull it out as a property. - rjhdby
      • @ AlekseyShimansky to explain why the $res->validator-error construct does not work - rjhdby
      • Why not? If you want to bring echo СобщениеОбОшибке that now, die and not do? - Alexey Shimansky