Getting value of static vars dinamically

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
phpdevel
Forum Newbie
Posts: 3
Joined: Fri Jan 16, 2009 9:03 am

Getting value of static vars dinamically

Post by phpdevel »

EVERAH | PLEASE USE PHP OR CODE BBCODE TAGS WHEN POSTING CODE IN THE FORUMS.
Hello,

any one could help me ?
I'm trying to get the value of a static var by passing its name in a method (getString($varname)), but for the moment I've not found the correct way, it only returns the text "Texts::$first" but not its value.
Anyone know what the problem is ?

Code: Select all

 
class Texts {
 
  public static $first = "hello";
 
}
 
class One {
 
    public static function getString($varname) {
        $x = "Texts::$$varname";
 
        return (string) $x;
    }
 
}
 
@echo One::getString("first");
 
// The output should be "hello", but it does not work and returns "Texts::$first"
 
Thanks !
Last edited by RobertGonzalez on Fri Jan 16, 2009 12:21 pm, edited 1 time in total.
Reason: bbCode tags were not used
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Getting value of static vars dinamically

Post by RobertGonzalez »

Untested:

Code: Select all

<?php
class MyTest {
  public static $myvar = 'foo';
}
 
class MyNext {
  public static function get($var) {
    $val = ${$var}; // Braces not required, but a little easier to read
    return MyTest::$val;
  }
}
 
var_dump(MyNext::get('myvar'));
?>
phpdevel
Forum Newbie
Posts: 3
Joined: Fri Jan 16, 2009 9:03 am

Re: Getting value of static vars dinamically

Post by phpdevel »

Hi Everah,

thank you for your answer and sorry to not make use of the tags, next time I'll use them.
Using the code you show me still giving the following error :
Fatal error: Access to undeclared static property: MyTest::$val in ....
Any other idea ?

Thanks !
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Re: Getting value of static vars dinamically

Post by Burrito »

Code: Select all

  class MyTest {
     public static $myvar = 'foo';
   }
    
   class MyNext {
     public static function get($var) {
       return MyTest::${$var};
     }
   }
    
   echo MyNext::get('myvar');
 
phpdevel
Forum Newbie
Posts: 3
Joined: Fri Jan 16, 2009 9:03 am

Re: Getting value of static vars dinamically

Post by phpdevel »

Hi,

it works now !
Thank you very much for your help !
Post Reply