Creating anonymous objects in php

前端 未结 12 1951
故里飘歌
故里飘歌 2020-11-28 01:59

As we know, creating anonymous objects in JavaScript is easy, like the code below:

var object = { 
    p : \"value\", 
    p1 : [ \"john\", \"johnny\" ]
};

         


        
12条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 02:48

    "Anonymous" is not the correct terminology when talking about objects. It would be better to say "object of anonymous type", but this does not apply to PHP.

    All objects in PHP have a class. The "default" class is stdClass, and you can create objects of it this way:

    $obj = new stdClass;
    $obj->aProperty = 'value';
    

    You can also take advantage of casting an array to an object for a more convenient syntax:

    $obj = (object)array('aProperty' => 'value');
    print_r($obj);
    

    However, be advised that casting an array to an object is likely to yield "interesting" results for those array keys that are not valid PHP variable names -- for example, here's an answer of mine that shows what happens when keys begin with digits.

提交回复
热议问题