php - How to call a property combined with a variable?

161

In my class I have 2 properties called:

  • private $sender_host
  • private $receiver_host

My method gives a parameter called '$target' and this can only be the string 'sender' or 'receiver'.

I now would like to call the right property, depending what the parameter $target says. This is the way I want it to be called:$this->$parameter . '_host' ... that means, when $target equals 'sender', it should return the value of the property $sender_host and when it equals 'receiver', it should return the value of $receiver_host but I guess the way I am trying it won't work. So is there another way I could reach my goal?

807

Answer

Solution:

Simply by$this->{$target . '_host'} (yes, I think you mentioned$target at first)

People are also looking for solutions to the problem: php - Laravel: extra field sync with array

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.