0

I don't know very good how to describe my problem, but here's what I want to do: I want to escape the language variables and convert them to static variables. Something like this

public static $languages = array('nl', 'en');
public static $nl;
public static $en;

public function __construct(){
    foreach(self::$languages as $lang){
        self::{$lang} = $content[$lang];
    }
}

I know this is possible with a non static variable like this:

$this->{$lang} = $content[$lang];

but I constantly get errors when trying to convert it to a static variable. Is there a way to do this? or is it impossible in php?

Helena Standaert
  • 559
  • 1
  • 13
  • 31

3 Answers3

1

No you cannot create static variable on the fly in php. You can find the similar response in this thread Is it possible to create static variables on runtime in PHP?

Community
  • 1
  • 1
1

You have several problems.:

  1. A class var must be a constant expression. An array definition is not.
  2. Static vars are accessed with $.
  3. $content is not defined.

Just for example, this works:

public static $nl;
public static $en;

public function __construct(){
    $languages = array('nl', 'en');
    foreach($languages as $lang){
        //self::${$lang} = $content[$lang];
        self::${$lang} = time();
        echo self::${$lang};
    }
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • This works, thanks! Exactly what I was looking for! p.s. $content had been defined, but I just didn't include it in the question ;-) – Helena Standaert Jul 15 '14 at 15:14
-1

No you cant do this, even using self::${$lang} = ... you will get PHP fatal error:

Fatal error: Access to undeclared static property: MyClass::$lang in test.php on line 9

However, are you sure you want to use static property? I assume you pass the $content array into the constructor when instantiating the object. If the values inside $content is specific to that particular object, you should stores those values into object properties instead of static properties.

Chris Lam
  • 3,526
  • 13
  • 10