Forum Moderators: coopster

Message Too Old, No Replies

Dynamic variable and function names

         

ironik

11:01 pm on Mar 29, 2005 (gmt 0)

10+ Year Member



I've had a good search around, but can't seem to find anything in the PHP manual about using dynamic variable or function names (perhaps I'm not sure what it is I'm looking for). I have a class that uses a function to store internal attributes dynamically:


class MyClass
{
var $attr1;

var $attr2

function setAttr($var, $val)
{
$this->{$var} = $val;
}
}

$thisClass = new MyClass;
$settings = array('attr1' => 'A string',
'attr2' => 1);
foreach ($settings as $key=>$val)
{
$thisClass->setAttr($key, $val);
}

It works fine for integers, but not for strings?

I'd also like to use the same method to construct dynamic function and class names... Can anyone help me out with the proper syntax to use?

coopster

11:00 pm on Mar 30, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You mean variable variables [php.net] and variable functions [php.net]?

ironik

11:50 pm on Apr 4, 2005 (gmt 0)

10+ Year Member



Yes thank you! Variable functions had the right syntax to use for methods and attributes