Initialize Objects like arrays in PHP?

后端 未结 8 1479
情话喂你
情话喂你 2021-01-01 09:04

In PHP, you can initialize arrays with values quickly using the following notation:

$array = array(\"name\" => \"member 1\", array(\"name\" => \"member         


        
8条回答
  •  庸人自扰
    2021-01-01 09:46

    From a (now dead) post showing both type casting and using a recursive function to convert single and multi-dimensional arrays to a standard object:

     0) {
            foreach ($array as $name=>$value) {
                $name = strtolower(trim($name));
                if (!empty($name)) {
                    $object->$name = arrayToObject($value);
                }
            }
            return $object;
        }
        else {
            return FALSE;
        }
    }
    

    Essentially you construct a function that accepts an $array and iterates over all its keys and values. It assigns the values to class properties using the keys.

    If a value is an array, you call the function again (recursively), and assign its output as the value.

    The example function above does exactly that; however, the logic is probably ordered a bit differently than you'd naturally think about the process.

提交回复
热议问题