Page 1 of 1

Getting value of static vars dinamically

Posted: Fri Jan 16, 2009 9:05 am
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 !

Re: Getting value of static vars dinamically

Posted: Fri Jan 16, 2009 12:24 pm
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'));
?>

Re: Getting value of static vars dinamically

Posted: Fri Jan 16, 2009 12:40 pm
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 !

Re: Getting value of static vars dinamically

Posted: Fri Jan 16, 2009 1:25 pm
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');
 

Re: Getting value of static vars dinamically

Posted: Fri Jan 16, 2009 2:11 pm
by phpdevel
Hi,

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