Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i have the following 3 variables:

        private $a_total;
        private $b_total;
        private $c_total;

now when the fields are filled out with some data for totals, names of those fields are "a", "b", and "c". I want to store it dynamically to the variables above something like:

      $type = $_POST['totaltype']; //either a, b or c
      $to_save = "{$type}_total";
      $this->$to_save['total'] = some number;

if i try to

 print_r($this->$to_save); 

it gives empty array. If i try to:

 print_r($this->$to_save['total']); 

it gives correct number.

can anyone help?

Note: i want to use dynamically because these data will be inside a big loop so i don't want to reuse $a_total, $b_total, $c_total since i will have more than a, b and c variables.

share|improve this question
1  
It might be better to restructure the way you're accessing this. Have you considered $this->totals[$type]. There's no reason to dynamically create a variable for this case. –  freshnode Nov 5 '12 at 14:01
    
i need to store it in database as separate serialized array. will that work for the case? –  Giorgi Nov 5 '12 at 14:03
1  
Well yes, if you serialise($this->totals) you'll get an array with an associative structure. If you're using one of the below answers, go for it - just didn't immediately see why you'd need to incur the overhead of dynamically creating these variables. –  freshnode Nov 5 '12 at 14:07
    
this would work also but for this project i need it dynamic, thanks though –  Giorgi Nov 5 '12 at 14:09
add comment

2 Answers

up vote 1 down vote accepted

You can wrap the variable name in curly-brackets inside the class:

$this->{$type . "_total"} = 5;

The same works when accessing it like an array:

$this->{$type . "_total"}['total'] = 5;

You can also save the full-name of the variable in a string, such as your $to_save and access it the same way:

$to_string = $type . '_total';
$this->{$to_string}['total'] = 5;
print_r($this->{$to_string});
share|improve this answer
    
this is what i was looking for, curly-brackets did the trick thank you –  Giorgi Nov 5 '12 at 14:05
add comment

Change $a_total to $total['a'], $b_total to $total['b'], and $c_total to $total['c'],

Then you can access the values dynamically.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.