Method of defining literal object using json data format in PHP

  • 2021-07-13 04:52:19
  • OfStack

PHPer knows that PHP does not support literals, at least not in the current version. For example, object can be defined in JS as follows


var o = { 'name' : 'qttc' , 'url' : 'www.ofstack.com' };
alert(o.name);

Dictionaries are defined in Python, and can also be defined as follows:

o = { 'name' : 'qttc' , 'url' : 'www.ofstack.com' }
print o['name']

But object is defined in PHP as follows:

$a = { "name" : "qttc", "url" : "www.ofstack.com"  };

Will report an error:

[root@lee www]# php a.php
PHP Parse error:  syntax error, unexpected '{' in /data0/htdocs/www/a.php on line 4

We can borrow the json format, enclose it in quotation marks and then go back to json_decoude.

$a = '{ "name" : "qttc", "url" : "www.ofstack.com"  }';
$a = json_decode($a);
print_r($a);

Implementation results:

[root@lee www]# php a.php
stdClass Object
(
    [name] => qttc
    [url] => www.ofstack.com
)

Because PHP does not support the literal or anonymous function, you cannot add function to object when defining object using the method defined above. You can also add array elements as follows:

$a = '{ "name" : "qttc", "url" : "www.ofstack.com" , "arr":["zhangsan","lisi"] }';
$a = json_decode($a);
print_r($a);

Implementation results:

[root@lee www]# php a.php
stdClass Object
(
    [name] => qttc
    [url] => www.ofstack.com
    [arr] => Array
        (
            [0] => zhangsan
            [1] => lisi
        )
 
)


Related articles: