Re: Re: Classes in PHP5 || Puzzling Problem || Trying to Set $this->$name = $value
| From: | Frank M. Kromann | Date: | Thu, 08 Mar 2007 23:41:51 +0000 |
| Subject: | Re: Re: Classes in PHP5 || Puzzling Problem || Trying to Set $this->$name = $value | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-250136@lists.php.net to get a copy of this message | ||
Sounds like a PHP version problem. PHP 4 will output 0 and PHP 5 will give
1. The constructor must be named the same as the class name in PHP 4 for
this to work.
You can have both constructors in your class so it will work in both
versions.
- Frank
> I don't know the details of your app, but you might want to reconsider a
resdesign.
>
> Having said that, your code actually works for me. If I use your class
as is, foo is 1. That is:
>
> $x = new test;
> echo $x->foo;
>
> outputs 1. Isn't that what you want?
>
>
>
> Regards,
>
> Bruce
>
> >>> "PHP" <sit1way@hotmail.com> 9/03/2007 6:10:49 p.m. >>>
> 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
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>