How to convert an array to object in PHP?

前端 未结 30 2809
说谎
说谎 2020-11-22 02:48

How can I convert an array like this to an object?

[128] => Array
    (
        [status] => "Figure A.
 Facebook\'s horizontal scrollbars showing u         


        
30条回答
  •  你的背包
    2020-11-22 03:09

    I would definitly go with a clean way like this :

    from_array($payload);
      }
    
    
      public function from_array($array)
      {
         foreach(get_object_vars($this) as $attrName => $attrValue)
            $this->{$attrName} = $array[$attrName];
      }
    
      public function say_hi ()
      {
         print "hi my name is {$this->name}";
      }
    }
    
    print_r($_POST);
    $mike = new Person($_POST);
    $mike->say_hi();
    
    ?>
    

    if you submit:

    formulaire

    you will get this:

    mike

    I found this more logical comparing the above answers from Objects should be used for the purpose they've been made for (encapsulated cute little objects).

    Also using get_object_vars ensure that no extra attributes are created in the manipulated Object (you don't want a car having a family name, nor a person behaving 4 wheels).

提交回复
热议问题