Tell me, please, is it possible to somehow address the field of a class object, through a field of another class without creating new variables?

Those. Now I have a Test class, in which there is a field named pole_name and the method wokr_object ($ obj) .

The wokr_object method gets the object $ obj , which has a field whose name matches the value stored in the field pole_name .

And I need to access this field in the wokr_object function.
I got this code:

public function wokr_object($obj){ $temp = $this->pole_name; echo $obj->$temp; } 

It seems to work, but I do not like that I have to create an additional variable tempo, I want to write something like this in one line.

Those. I want to write something like echo $obj->$this->pole_name - but it does not work, it displays an error.

Tell me, please, can I somehow fix this, can I somehow arrange the brackets?

  • Bring the question, please, in the proper form. With the help of the existing visive you can adequately arrange what is now available. - borodatych
  • @borodatych you, as a community member, shy of outward appearance, you can quite easily press "edit" and format the question, thereby helping both the novice and the rest) - Alexey Shimansky

1 answer 1

So?

 echo $obj->{$this->pole_name}; 
  • Thank. Works. I did not think of curly braces, I tried to insert it into round ones, but with round ones I gave an error. If it’s not hard to tell, why errors with curly braces do not crash, and the rounds in this design cause an error? - Vladimir Vladimir
  • one
    @Vladimir Vladimir round brackets for mathematical logical operations, and curly brackets help the interpreter to clearly understand where the beginning of the variable, and where the end .......... see php.net/manual/ru/language.types.string.php section Сложный (фигурный) синтаксис - Alexey Shimansky
  • Curly brackets are used because here the property is not accessed directly, but through a compound name. Round simply indicate the priority of action, they can be used, for example, when concatenating strings, when calculating or in conditions, but not when referencing. - Daniel-664
  • It is clear, thanks, I will know. - Vladimir Vladimir
  • one
    The answer in this context is given. But nevertheless, one should point out the obvious shortcomings of this method in this context. In the end, the treatment of a variable (speaking the name) at least facilitates understanding. - Naumov