将PHP数组转换为类变量

ani*_*son 28 php arrays variables class object

简单的问题,如何将关联数组转换为类中的变量?我知道有铸造要做(object) $myarray或不管它是什么,但这将创建一个新的stdClass并没有帮助我.是否有任何简单的一行或两行方法可以将$key => $value我的数组中的每一对变为$key = $value我的类的变量?我觉得使用foreach循环是不合逻辑的,我最好将它转换为stdClass并将其存储在变量中,不是吗?

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
    }
}
Run Code Online (Sandbox Code Playgroud)

mač*_*ček 67

这个简单的代码应该工作:

<?php

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

?>
Run Code Online (Sandbox Code Playgroud)

用法示例

$foo = new MyClass(array("hello" => "world"));
$foo->hello // => "world"
Run Code Online (Sandbox Code Playgroud)

或者,这可能是一种更好的方法

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

?>
Run Code Online (Sandbox Code Playgroud)

用法是一样的

// 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
Run Code Online (Sandbox Code Playgroud)

  • @AntonioCS,没有必要,但它肯定强调了变量命名属性的访问.它还表明,当变量属性变得更复杂时,可以使用`{}`; 例如,`$ this - > {$ this-> foo('bar')} - > do_something();` (13认同)

Ozz*_*ech 10

最好的解决方案是具有可用于数据加载的静态函数的特征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;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用这个特性:

class Example {
  use FromArray;
  public $data;
  public $prop;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以调用静态fromArray函数来获取 Example 类的新实例:

$obj = Example::fromArray(['data' => 123, 'prop' => false]);
var_dump($obj);
Run Code Online (Sandbox Code Playgroud)

我还有更复杂的版本,带有嵌套和值过滤https://github.com/OzzyCzech/fromArray

  • @Meglio实际上,它不是一个虚拟对象,它是设置属性后最终返回的实例。如果使用“get_class($this)”或替代的“self::class”,则必须在循环之前创建一个实例。 (2认同)