View Full Version : variable variables and class property assignment

01-16-2008, 12:43 AM
i have a class:

class tableClass {
public $testvar;
the function of the full class is to assemble a table. I have .inc files for each table that must set multiple public properties of this table class. however, i want to keep the .inc files for each table uniform. like

$table->testvar = 'hello;

this presents a problem, because it requires that each class instance is called "$table". i thought i could solve the issue by using variable variables and leave the inc files as is, but use

$myTable1 = new tableClass();
$$table = $myTable1;
and change the inc files to use $$table everywhere without hardcoding the instance names

$$table->testvar = 'hello';

01-16-2008, 06:32 PM
I've never used a variable variable with an object before, but it may be a similar problem to how the variable variables are treated when as an array, its not sure if you are looking at $table->method, or if you want $$table->method. So, the fix around for that is to use ${$table}->method(). See if that works.
The other plus side is that if you assign $table a new table object, everytime its constructed $table takes the new object, so you may not require the use of variable variables for tracking them - I find that this tends to be the case more often. Try the force on it first, see if that fixes your problem.

01-17-2008, 12:12 AM
well i came up with a better solution...

all of my .inc files are now:

$this->varName = 'myVar';
i added a "loadCfg" method to my class simply that 'include's the file, this updates all of the object instance's properties. ends up being much slicker.

hope this helps others, dont want to get the noodle out for nothing :)

01-17-2008, 02:57 AM
Ah I see, so all of these are actually in an object then eh? Yes, always use $this when referring an object reference of itself, unless you are wanting specific behaviour in an extend able method. I've been caught in an infinite call from parent to child and back on a savable class I created once. Easy get around though, simply use self:: calls instead if it may be extended and the child may call the same class it also defines. Err, yeah kinda confusing sounding, I'll give you an example if you need one though :P