How to define a literal object using json data format in PHP

Source: Internet
Author: User
Tags parse error
This article describes how to define literal objects in json data format in PHP. This is a work und. json can also be used to generate arrays in classes, for more information, see

This article describes how to define literal objects in json data format in PHP. This is a work und. json can also be used to generate arrays in classes, for more information, see

PHPer knows that PHP does not support literal terms, at least in the current version. For example, you can define an object in JS as follows:

The Code is as follows:


Var o = {'name': 'qttc ', 'url': 'www .jb51.net '};
Alert (o. name );


You can define a dictionary in Python as follows:

The Code is as follows:


O = {'name': 'qttc ', 'url': 'www .jb51.net '}
Print o ['name']


But in PHP, objects are defined as follows:

The Code is as follows:


$ A = {"name": "qttc", "url": "www.jb51.net "};


An error is reported:

The Code is as follows:


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


We can use json format, enclose it with quotation marks, and then use json_decoude.

The Code is as follows:


$ A = '{"name": "qttc", "url": "www.jb51.net "}';
$ A = json_decode ($ );
Print_r ($ );


Execution result:

The Code is as follows:


[Root @ lee www] # php a. php
StdClass Object
(
[Name] => qttc
[Url] =>
)


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

The Code is as follows:


$ A = '{"name": "qttc", "url": "www.jb51.net", "arr": ["zhangsan", "lisi"]}';
$ A = json_decode ($ );
Print_r ($ );


Execution result:

The Code is as follows:


[Root @ lee www] # php a. php
StdClass Object
(
[Name] => qttc
[Url] =>
[Arr] => Array
(
[0] => zhangsan
[1] => lisi
)

)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.