Methods for defining literal objects using JSON data format in PHP _php tips

Source: Internet
Author: User
Tags parse error in python

Phper all know that PHP does not support literal volume, at least the current version is not supported. For example, in JS you can define object in this way

Copy Code code as follows:

var o = {' name ': ' QTTC ', ' url ': ' Www.jb51.net '};
alert (o.name);

The dictionary is defined in Python, or it can be defined as:
Copy Code code as follows:

o = {' name ': ' QTTC ', ' url ': ' Www.jb51.net '}
Print o[' name '

But in PHP, this defines object:
Copy Code code as follows:

$a = {"Name": "QTTC", "url": "Www.jb51.net"};

Will complain:
Copy Code code 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 borrow the JSON format, enclose the bag in quotes and then json_decoude it.
Copy Code code as follows:

$a = ' {' name ': ' QTTC ', ' url ': ' Www.jb51.net '} ';
$a = Json_decode ($a);
Print_r ($a);

Execution results:
Copy Code code as follows:

[Root@lee www]# php a.php
StdClass Object
(
[Name] => QTTC
[url] => www.jb51.net
)

Because PHP does not support literal or anonymous functions, you can add an array element by using the method defined above to define object without adding a function to object:
Copy Code code as follows:

$a = ' {' name ': ' QTTC ', ' url ': ' Www.jb51.net ', ' arr ': [' Zhangsan ', ' Lisi ']} ';
$a = Json_decode ($a);
Print_r ($a);

Execution results:
Copy Code code as follows:

[Root@lee www]# php a.php
StdClass Object
(
[Name] => QTTC
[url] => www.jb51.net
[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.