Problem calling/setting dynamic variables

Hi,

The problem i’m having may be related to the version of PHP i’m using.

I have an object


foo {

    private $var1 = array();
    private $var2 = array();

    function foobar($t , $d){
        $this->$t[] = $d;
    }

}

The problem is $this->$t = $d; It isn’t adding it to the relevant array.
EG. when $t = ‘var2’, $this->$t should add a value to the $var2 array. But it’s not doing that unless I hardcode the varible name.
All the variables that are to be used are hardcoded in the object, none of the variables are to be created on the fly.

Doing this on another local machine (at home) works fine, but on my work machine, the setting of a variable using $this->$t does not work.

Is there an extension I could be missing?
Or… am i being a total idiot?

Cheers.

Use the following function

public function foobar($t , $d)
{ 
        if (isset($this->$t))
                array_push($this->$t, $d); 
}

Thanks for the reply.
I should have added, I also need to be able to set the keys so the array_push method wont work, auto inc keys are useless for the app.

Cheers

Use this

public function foobar($t , $d)
{
        if (!isset($this->$t))
                $this->$t = array();
        array_push($this->$t, $d);
}

or this

private $vars = array();
public function foobar($t, $d)
{
        if (!array_key_exists($t, $this->vars))
                $this->vars[$t] = array();
        array_push($this->vars[$t], $d);
}

Time out :stuck_out_tongue:

You’re trying to pass $t as the name of the variable?


foo { 

    private $var1 = array(); 
    private $var2 = array(); 

    function foobar($t , $d){ 
        $this->$$t[] = $d; 
    } 

} 

See if you can spot the subtle change…

This throws fatal error. There is an explanation and a workaround here (last post).