2010-04-28 118 views

回答

19

使用parse_str()${'track_' . $i} = 'val';

+0

爲什麼downvote? – 2010-04-28 07:45:59

+3

對於$ {...},而不是變量變量。 – 2010-04-28 07:48:29

+3

$ {...}仍然是一個變量變量。 – 2010-04-28 07:49:39

3
<? 
for($i = 0; $i < 10; $i++) { 
    $name = "track_$i"; 
    $$name = 'hello'; 
} 

print("==" . $track_3); 
0
<?php 

for ($i = 1; $i <= 3; $i++) { 
    ${"track_{$i}"} = 'this is track ' . $i; // use double quotes between braces 
} 

echo $track_1; 
echo '<br />'; 
echo $track_3; 

?> 


這也適用於嵌套瓦爾:

<?php 

class Tracks { 
    public function __construct() { 
     $this->track_1 = 'this is friend 1'; 
     $this->track_2 = 'this is friend 2'; 
     $this->track_3 = 'this is friend 3'; 
    } 
} 

$tracks = new Tracks; 

for ($i = 1; $i <= 3; $i++) { 
    echo $tracks->{"track_{$i}"}; 
    echo '<br />'; 
} 

?>