简体   繁体   中英

PHP assoc array to class instance

I saw that the conversion from a class instance (object) to associative array is a simple cast :

$array =  (array) $yourObject;

So if i have class A and an associative array contaning the neccesary fields to fill a class A object would it be enough to do the opposite? eg

$aInstance=(A)$assocArray;

If not whats the easiest way to do so?

Things are not that easy, since there is no way for php to somehow magically guess what to do with the values of that array. Objects are a structured set of data unlike an array. So you need a description of the structure and rules how to use it.

You need to implement a constructor in the class definition, then you can construct a new object based on some given array. Take a look at this arbitrary example:

<?php
class A {
    protected $title;
    protected $data;
    public function __construct ($data) {
        $this->title = $data['title'];
        $this->data = sprintf('this is foo: %s', $data['foo']);
    }
    public function __toString() {
        return sprintf(
            "I am an object titled '%s'\nI hold that foo value: %s\n",
            $this->title,
            $this->data
        );
    }
}

$data = [
    'title' => 'hello world',
    'foo' => 'foovalue',
    'bar' => 'barvalue'
];
$object = new A($data);
echo $object;
var_dump($object);

The obvious output is:

I am an object titled 'hello world'
I hold that foo value: this is foo: foovalue
/home/arkascha/test.php:25:
class A#1 (2) {
  protected $title =>
  string(11) "hello world"
  protected $data =>
  string(21) "this is foo: foovalue"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM