How to convert an array to object in PHP?

前端 未结 30 3341
说谎
说谎 2020-11-22 02:48

How can I convert an array like this to an object?

[128] => Array
    (
        [status] => "Figure A.
 Facebook\'s horizontal scrollbars showing u         


        
30条回答
  •  没有蜡笔的小新
    2020-11-22 03:07

    Little complicated but easy to extend technique:

    Suppose you have an array

    $a = [
         'name' => 'ankit',
         'age' => '33',
         'dob' => '1984-04-12'
    ];
    

    Suppose you have have a Person class which may have more or less attributes from this array. for example

    class Person 
    {
        private $name;
        private $dob;
        private $age;
        private $company;
        private $city;
    }
    

    If you still wanna change your array to the person object. You can use ArrayIterator Class.

    $arrayIterator = new \ArrayIterator($a); // Pass your array in the argument.
    

    Now you have iterator object.

    Create a class extending FilterIterator Class; where you have to define the abstract method accept. Follow the example

    class PersonIterator extends \FilterIterator
    {
        public function accept()
        {
            return property_exists('Person', parent::current());
        }
    }
    

    The above impelmentation will bind the property only if it exists in the class.

    Add one more method in the class PersonIterator

    public function getObject(Person $object)
    {
            foreach ($this as $key => $value)
            {
                $object->{'set' . underscoreToCamelCase($key)}($value);
            }
            return $object;
    }
    

    Make sure you have mutators defined in your class. Now you are ready to call these function where you want to create object.

    $arrayiterator = new \ArrayIterator($a);
    $personIterator = new \PersonIterator($arrayiterator);
    
    $personIterator->getObject(); // this will return your Person Object. 
    

提交回复
热议问题