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?

2
  • self::${$lang} = $content[$lang] should work for statics. Commented Jul 15, 2014 at 14:57
  • __construct() will not be called for static variables or methods. You are probably looking for a singleton pattern. Is this simply a config storage mechanism? Commented Jul 15, 2014 at 14:58

3 Answers 3

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};
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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 ;-)
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?

Comments

-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.