Initialize Objects like arrays in PHP?

后端 未结 8 1437
情话喂你
情话喂你 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:44

    I also up-voted Gumbo as the preferred solution but what he suggested is not exactly what was asked, which may lead to some confusion as to why member1o looks more like a member1a.

    To ensure this is clear now, the two ways (now 3 ways since 5.4) to produce the same stdClass in php.

    1. As per the question's long or manual approach:

      $object = new stdClass;
      $object->member1 = "hello, I'm 1";
      $object->member1o = new stdClass;
      $object->member1o->member1 = "hello, I'm 1o.1";
      $object->member2 = "hello, I'm 2";
      
    2. The shorter or single line version (expanded here for clarity) to cast an object from an array, ala Gumbo's suggestion.

      $object = (object)array(
           'member1' => "hello, I'm 1",
           'member1o' => (object)array(
               'member1' => "hello, I'm 1o.1",
           ),
           'member2' => "hello, I'm 2",
      );
      
    3. PHP 5.4+ Shortened array declaration style

      $object = (object)[
           'member1' => "hello, I'm 1",
           'member1o' => (object)['member1' => "hello, I'm 1o.1"],
           'member2' => "hello, I'm 2",
      ];
      

    Will both produce exactly the same result:

    stdClass Object
    (
        [member1] => hello, I'm 1
        [member1o] => stdClass Object
            (
                [member1] => hello, I'm 1o.1
            )
    
        [member2] => hello, I'm 2
    )
    

    nJoy!

    0 讨论(0)
  • 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:

    <?php
    function arrayToObject($array) {
        if (!is_array($array)) {
            return $array;
        }
    
        $object = new stdClass();
        if (is_array($array) && count($array) > 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.

    0 讨论(0)
  • 2021-01-01 09:46

    You could try:

    function initStdClass($thing) {
        if (is_array($thing)) {
          return (object) array_map(__FUNCTION__, $thing);
        }
        return $thing;
    }
    
    0 讨论(0)
  • 2021-01-01 09:46

    Another option for deep conversion is to use json_encode + json_decode (it decodes to stdClass by default). This way you won't have to repeat (object) cast in each nested object.

    $object = json_decode(json_encode(array(
         'member1' => "hello, I'm 1",
         'member1o' => array(
             'member1' => "hello, I'm 1o.1",
         ),
         'member2' => "hello, I'm 2",
    )));
    

    output:

    php > print_r($object);
    stdClass Object
    (
        [member1] => hello, I'm 1
        [member1o] => stdClass Object
            (
                [member1] => hello, I'm 1o.1
            )
    
        [member2] => hello, I'm 2
    )
    
    0 讨论(0)
  • 2021-01-01 09:53

    You can use type casting:

    $object = (object) array("name" => "member 1", array("name" => "member 1.1") );
    
    0 讨论(0)
  • 2021-01-01 09:59

    I use a class I name Dict:

    class Dict {
    
        public function __construct($values = array()) {
            foreach($values as $k => $v) {
                $this->{$k} = $v;
            }
        }
    }
    

    It also has functions for merging with other objects and arrays, but that's kinda out of the scope of this question.

    0 讨论(0)
提交回复
热议问题