0

How can I convert array (assoc or seq) into class variables:

I have this array

[
    "uuidtype"=>4,
    "data"=>[
        "name"=>"Arthur",
        "age"=>"unknown"
    ]
]

I have this class:

class Example{
    public static function ___g($var_name, $val){
        // static $$varname = $val; Doesn't work
        // self::${(string)$varname} = $val; Doesn't work
    }
}

I want this:

class Example{
    public static $uuidtype = 4;
    public static $data;

    ...
}
3
  • my vote would be to define a basic class and use magic __get/__call methods, at which point this array would become a property of this class instance, and your __get/__call methods would interact with the array data and act accordingly Commented Apr 9, 2018 at 23:02
  • Also, tell us about the problem you're trying to solve and tell us why you think this is the solution to your problem? Commented Apr 9, 2018 at 23:04
  • Class properties are for defining static values, not runtime data. Runtime data would be in the object itself, so either in a method, or specifically get/set methods, or the constructor - whichever makes sense for what you're doing. Commented Apr 9, 2018 at 23:05

2 Answers 2

0

You could create an Array and then cast it as object, so:

$arr = [
    "uuidtype"=>4,
    "data"=>[
        "name"=>"Arthur",
        "age"=>"unknown"
    ]
]

$as_class = (object) $arr;

echo $as_class->uuidtype; //Works ;)

I am not sure about performance, but works for me.

Sign up to request clarification or add additional context in comments.

Comments

0

You can also use the Php __get magic method. It allows dynamically creating object properties. See http://php.net/manual/en/language.oop5.overloading.php#object.get. A similar question was asked on: How do I dynamically write a PHP object property name?

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.