php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #23351 Coding Question
Submitted: 2003-04-25 15:05 UTC Modified: 2003-04-25 15:24 UTC
From: dave at socrates dot thinkhost dot com Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 4.3.2RC1 OS: FreeBSD4.7
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: dave at socrates dot thinkhost dot com
New email:
PHP Version: OS:

 

 [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?

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2003-04-25 15:24 UTC] dave at socrates dot thinkhost dot com
Bogus, error in my code

$this->{$name} works as expected
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Dec 22 11:01:30 2024 UTC