fbpx

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


Upptäck mer från Tornevall

Prenumerera för att få de senaste inläggen skickade till din e-post.

You may also like