Converting a PHP array to class variables

后端 未结 6 1570
说谎
说谎 2020-12-07 10:01

Simple question, how do I convert an associative array to variables in a class? I know there is casting to do an (object) $myarray or whatever it is, but that w

6条回答
  •  粉色の甜心
    2020-12-07 10:54

    Define a static method to convert get an instance from an array. Best, define an interface for it. This is declarative, does not pollute the constructor, allows you to set private properties and still implement custom logic that would not be possible with Reflection. If you want a generic solution, define a trait and use it in your classes.

    class Test implements ContructableFromArray {
       private $property;
       public static function fromArray(array $array) {
           $instance = new self();
           $instance->property = $array['property'];
           return $instance;
       }
    }
    
    interface ConstructableFromArray {
       public static function fromArray(array $array);
    }
    

提交回复
热议问题