1

my php is update from php 5.4 to php 7.0.33 , but php code get an error with Dynamic variables

php 5.4 some code like this...

$attributes=array('boy','girl','none' );
$this->boy = 'eric';
$this->girl = 'lili';
$this->none = 'who';
            
echo $attributes[0];                    //=>php 5 is "boy"  | php 7 is "boy"
print_r( $this->$attributes[0] );       //=>php 5 is "eric" | php 7 is empty
print_r( $this->${attributes}[0] );     //=>php 5 is "eric" | php 7 is empty

when I use in php 7 shome code get epmty, how can I do to resolve this problem

I already watching the refer page Using braces with dynamic variable names in PHP , but still confused

lili
  • 13
  • 2

2 Answers2

2

For dynamic variables like this, you need to wrap the string in curly braces. You almost had it there in your last line. However, remember that it's not the array $attributes that you're using to indicate the dynamic variable, it's the string at $attributes[0].

So this should work:

$this->{$attributes[0]}

Dynamic variables names are powerful, but easy to get confused with. If you have the option, I'd recommend using just an array:

$this->attributes = [
    "boy"  => "eric",
    "girl" => "lili",
    "none" => "who"
];

echo $this->attributes["boy"];
Quasipickle
  • 4,383
  • 1
  • 31
  • 53
1

The syntax you are searching for is

 print_r( $this->{$attributes[0]} ); 
Lu_kors
  • 80
  • 6