|   | php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
| 
  [2003-04-25 15:05 UTC] dave at socrates dot thinkhost dot com
 This is a coding question, because I believe that I should be able to do this, but I can not find reference to it anywhere in the documentation (on or off the PHP site). The problem is best expressed through an example, note that PHP doesn't complain, it just doesn't do what I want it to.
Consider the code fragment:
class MyClass {
  var $day;
  var $month;
  var $year;
 // ...constructor...
  function getFieldByName ($name) {
    return   $this->$name;
  }
  function updateFieldByName ($name, $value) {
    $this->$name = $value;
  }
}
Now consider the following sequence of commands:
$r = new MyClass();
$r->updateFieldByName("year", "2003")
echo $r->getFieldByName("year");
Which outputs nothing, because not only did it fail to retrieve the local variable, but it failed to update the local variable. Member functions can be called like so:
$this->$function_name_in_this_variable();
Why can't we access local variables the same way?
I have also tried:
$this->{$name}
Based on the fact that ${$name} is the same as $$name.
In the class that I am dealing with, there are so many local variables that an update function for each field is impractical at best. Is there a way to accomplish what I am trying to do, or am I merely using incorrect syntax?
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             | |||||||||||||||||||||||||||
|  Copyright © 2001-2025 The PHP Group All rights reserved. | Last updated: Fri Oct 31 18:00:01 2025 UTC | 
Bogus, error in my code $this->{$name} works as expected