Convert a PHP object to an associative array

后端 未结 30 1523
走了就别回头了
走了就别回头了 2020-11-22 02:18

I\'m integrating an API to my website which works with data stored in objects while my code is written using arrays.

I\'d like a quick-and-dirty function to convert

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 02:40

    For your case it was right/beautiful if you would use the "decorator" or "date model transformation" patterns. For example:

    Your model

    class Car {
        /** @var int */
        private $color;
    
        /** @var string */
        private $model;
    
        /** @var string */
        private $type;
    
        /**
         * @return int
         */
        public function getColor(): int
        {
            return $this->color;
        }
    
        /**
         * @param int $color
         * @return Car
         */
        public function setColor(int $color): Car
        {
            $this->color = $color;
            return $this;
        }
    
        /**
         * @return string
         */
        public function getModel(): string
        {
            return $this->model;
        }
    
        /**
         * @param string $model
         * @return Car
         */
        public function setModel(string $model): Car
        {
            $this->model = $model;
    
            return $this;
        }
    
        /**
         * @return string
         */
        public function getType(): string
        {
            return $this->type;
        }
    
        /**
         * @param string $type
         * @return Car
         */
        public function setType(string $type): Car
        {
            $this->type = $type;
    
            return $this;
        }
    }
    

    Decorator

    class CarArrayDecorator
    {
        /** @var Car */
        private $car;
    
        /**
         * CarArrayDecorator constructor.
         * @param Car $car
         */
        public function __construct(Car $car)
        {
            $this->car = $car;
        }
    
        /**
         * @return array
         */
        public function getArray(): array
        {
            return [
                'color' => $this->car->getColor(),
                'type' => $this->car->getType(),
                'model' => $this->car->getModel(),
            ];
        }
    }
    

    Usage

    $car = new Car();
    $car->setType('type#');
    $car->setModel('model#1');
    $car->setColor(255);
    
    $carDecorator = new CarArrayDecorator($car);
    $carResponseData = $carDecorator->getArray();
    

    So it will be more beautiful and more correct code.

提交回复
热议问题