Re: Classes in PHP5 || Puzzling Problem || Trying to Set $this->$name = $value
| From: | PHP | Date: | Fri, 09 Mar 2007 05:10:49 +0000 |
| Subject: | Re: Classes in PHP5 || Puzzling Problem || Trying to Set $this->$name = $value | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-250132@lists.php.net to get a copy of this message | ||
Hey all.
Problem:
Class test {
var $foo = 0;
function __construct() {
$this->myfunc("foo", 1);
}
function myfunc($name, $val) {
$this->$name = $val;
}
}
Now, PHP correctly evaluates $this->$name as 0; i.e. the default property
value of $this->foo.
However, what I really need to have happen is for $this->$name = $val to be
evaluated as $this->foo = 1;
I have tried variations of $this->$$name = $val, $this->${$name} = $val,
etc., but none of them work -- I keep getting an "Undefined variable: foo"
error from PHP, when very clearly foo has been defined.
This is a very simple example of what I'm actually attempting to implement,
so please do not reply with, "Well, why not just do: $this->foo = $val"
I'm sure intermediate to advanced PHP developers have run across this issue
before -- feel free to chime in ;--)
Thanks!
--Noah