Converting a PHP array to class variables

2022-08-30 13:17:56

Simple question, how do I convert an associative array to variables in a class? I know there is casting to do an or whatever it is, but that will create a new stdClass and doesn't help me much. Are there any easy one or two line methods to make each pair in my array into a variable for my class? I don't find it very logical to use a foreach loop for this, I'd be better off just converting it to a stdClass and storing that in a variable, wouldn't I?(object) $myarray$key => $value$key = $value

class MyClass {
    var $myvar; // I want variables like this, so they can be references as $this->myvar
    function __construct($myarray) {
        // a function to put my array into variables
    }
}

答案 1

This simple code should work:

<?php

  class MyClass {
    public function __construct(Array $properties=array()){
      foreach($properties as $key => $value){
        $this->{$key} = $value;
      }
    }
  }

?>

Example usage

$foo = new MyClass(array("hello" => "world"));
$foo->hello // => "world"

Alternatively, this might be a better approach

<?php

  class MyClass {

    private $_data;

    public function __construct(Array $properties=array()){
      $this->_data = $properties;
    }

    // magic methods!
    public function __set($property, $value){
      return $this->_data[$property] = $value;
    }

    public function __get($property){
      return array_key_exists($property, $this->_data)
        ? $this->_data[$property]
        : null
      ;
    }
  }

?>

Usage is the same

// init
$foo = new MyClass(array("hello" => "world"));
$foo->hello;          // => "world"

// set: this calls __set()
$foo->invader = "zim";

// get: this calls __get()
$foo->invader;       // => "zim"

// attempt to get a data[key] that isn't set
$foo->invalid;       // => null

答案 2

Best solution is to have trait with static function that can be used for data loading:fromArray

trait FromArray {
 public static function fromArray(array $data = []) {
   foreach (get_object_vars($obj = new self) as $property => $default) {
     if (!array_key_exists($property, $data)) continue;
     $obj->{$property} = $data[$property]; // assign value to object
   }
   return $obj;
  }
}

Then you can use this trait like that:

class Example {
  use FromArray;
  public $data;
  public $prop;
}

Then you can call static function to get new instance of Example class: fromArray

$obj = Example::fromArray(['data' => 123, 'prop' => false]);
var_dump($obj);

I also have much more sophisticated version with nesting and value filtering https://github.com/OzzyCzech/fromArray