Home  >  Article  >  php教程  >  PHP中使用json数据格式定义字面量对象的方法

PHP中使用json数据格式定义字面量对象的方法

WBOY
WBOYOriginal
2016-06-06 20:19:191213browse

这篇文章主要介绍了PHP中使用json数据格式定义字面量对象的方法,这是一种变通方法,使用json还可以在类中生成数组哦,需要的朋友可以参考下

PHPer都知道PHP是不支持字面量了,至少目前版本都不支持。比如,在JS中可以这样定义object

复制代码 代码如下:


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


Python中定义字典,也可以这样定义:

复制代码 代码如下:


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


但在PHP中这么定义object:

复制代码 代码如下:


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


会报错:

复制代码 代码如下:


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


我们可以借用json格式,用引号把包下然后再json_decoude就好。

复制代码 代码如下:


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


执行结果:

复制代码 代码如下:


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


由于PHP不支持字面量or匿名函数,,所以使用以上定义的方法定义object时不能添加function到object里,还可以这样添加数组元素:

复制代码 代码如下:


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


执行结果:

复制代码 代码如下:


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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn