object to object converting (__PHP_Incomplete_Class)

I’ve read a lot of suggestions on how to fix incomplete classobjects and I actually needed to fix those problems myself, in a ecommerce-project.

One suggestion I’ve found is to simply use json_decode/json_encode to convert incomplete classes without preloading anything. However, I didn’t want to take the risk using this, if there are older PHP versions that are dependent in for example PECL, that is described at http://php.net/manual/en/function.json-encode.php – so I finally succeeded to make my own solution.

However, the code is a way to get the data out of the object properly, so it may not fit all needs – and it will primarily, use the json-solution first, if it is available in the environment and fail over to manual handling if needed.

It also works recursively, which in my own case is required, to save the whole array.

    /**
     * Convert a object to a data object (used for repairing __PHP_Incomplete_Class objects)
     * @param array $d
     * @return array|mixed|object
     */
    function arrayObjectToStdClass($d = array())
    {
        /**
         * If json_decode and json_encode exists as function, do it the simple way.
         * http://php.net/manual/en/function.json-encode.php
         */
        if (function_exists('json_decode') && function_exists('json_encode')) {
            return json_decode(json_encode($d));
        }
        $newArray = array();
        if (is_array($d) || is_object($d)) {
            foreach ($d as $itemKey => $itemValue) {
                if (is_array($itemValue)) {
                    $newArray[$itemKey] = (array)$this->arrayObjectToStdClass($itemValue);
                } elseif (is_object($itemValue)) {
                    $newArray[$itemKey] = (object)(array)$this->arrayObjectToStdClass($itemValue);
                } else {
                    $newArray[$itemKey] = $itemValue;
                }
            }
        }
        return $newArray;
    }

http://stackoverflow.com/questions/965611/forcing-access-to-php-incomplete-class-object-properties/35863054#35863054

This entry was posted in Everything, Tech-stuff by Tornevall. Bookmark the permalink.

About Tornevall

- Stories from Reality - Musician | Bedroom DJ | Tug of War | Photographer | DevOps Thomas blends a passion for music, photography, and technology. With a background in 1990s dance music, his journey evolved from early experiments with FastTracker 2 to becoming a DJ and competitor in tug of war. His creative output includes documenting tug of war competitions across Sweden, while also working as a systems developer focusing on WordPress and e-commerce platforms.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.