PHPDev
PHPDev

Reputation: 152

PHP Dynamic Variable With this Keyword

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.

Upvotes: 1

Views: 121

Answers (1)

PHPDev
PHPDev

Reputation: 152

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'}

Upvotes: 2

Related Questions