1

I am trying to generate variable variables in a class method such as:

for ($i=1; $i <= 6; $i++) { 
    echo ${"this->year" . $i . "Season"};
}

I expect to get

$this->year1Season
$this->year2Season

and so on, but instead I get no output.

Note: I have already defined:

private $year1Season;
private $year2Season;

and so on at the top of the class and have defined:

$this->year1Season = $year1Season;
$this->year2Season = $year2Season;

and so on in the constructor.

The code works fine when I use the variables as:

echo $this->year1Season;

but not when I try to generate the variables dynamically.

3
  • 2
    $this->{'year' . $i .'Season'} Commented Dec 11, 2017 at 5:01
  • Thank you @marekful - that worked perfectly. Commented Dec 11, 2017 at 5:06
  • you can not assign $this->year1Season = $year1Season; It would be better if you show your class code to us Commented Dec 11, 2017 at 5:06

1 Answer 1

2

For anyone wondering, @marekful 's answer solved my question (the site doesn't let me select comments as answers, but I'd like to give him the props).

His answer is the following:

$this->{'year' . $i .'Season'}
Sign up to request clarification or add additional context in comments.

3 Comments

Its not advised to post answer to your own question.
@HimanshuUpadhyay That's just so that other people can more easily find the answer in case they have the same question.
Stackoverflow allow to Question and Post your own answer to help community,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.