Home  >  Article  >  Backend Development  >  How to convert php array to object

How to convert php array to object

藏色散人
藏色散人Original
2020-07-18 10:17:173259browse

The way to convert a php array into an object is to convert it directly by creating a new anonymous class. The specific statement is "protected function arrayTransitionObject(Array $array) {if (is_array($array)) }".

How to convert php array to object

php array conversion object method

Although php cannot directly new Object like js, php supports anonymous classes We can just create a new anonymous class for conversion

  /**
     * 数组转对象
     * @param Array $array
     * @author Quan
     * @return Object
     */
    protected function arrayTransitionObject(Array $array) 
    {
        if (is_array($array)) {
            $obj = new class{};
            foreach ($array as $key => $val) {
                $obj->$key = $val;
            }
        } else {
            $obj = $array;
        }
        return $obj;
    }

Recommended: "PHP Tutorial"

The above is the detailed content of How to convert php array to object. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn