Newbie123
Newbie123

Reputation: 123

Echo some properties value from a class with a for statement

I'm a newbie in here, especially on php, and I need your help.

I have a class that I've extended on the value class<.

In that class I've stored some of properties and I want to print it on the for statement.

Here is my code,

class value extends bla{
    public function example(){
        $value_bla[1] = $this->value1_bla;
        $value_bla[2] = $this->value2_bla;
        $value_bla[3] = $this->value3_bla;
        $value_bla[4] = $this->value4_bla;
        $value_bla[5] = $this->value5_bla;

        for( $i = 1; $i <= 5; $i++){
            echo 'the value is: '.$value_bla[$i]."\n";
        }
}

$example = new value();
$example->example();

but I want my code simpler like this,

class value extends bla{
    public function example(){  
        for( $i = 1; $i <= 5; $i++){
            echo 'the value is: '.$this->value.$i._bla."\n";
        }
}

$example = new value();
$example->example();

Unfortunately it is bring me an error

Can somebody tell me how to make that simpler code works?

Upvotes: 0

Views: 285

Answers (1)

George
George

Reputation: 36794

You need to use curly braces if you want to to reference a variable using a variable (Check the documentation):

class value extends bla{
    public function example(){  
        for( $i = 1; $i <= 5; $i++){
            echo 'the value is: '.$this->{'value'.$i.'_bla'}."\n";
        }
}

Although, when you find yourself doing this, there's probably a better way. You could, for example, use an associative array in your bla class which makes much more sense.

Upvotes: 1

Related Questions