PHP convet class to json data
Posted zengjf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP convet class to json data相关的知识,希望对你有一定的参考价值。
/********************************************************************* * php convet class to json data * 说明: * 突然想使用class自动转换为json数据,这样的代码可扩展性会好一点, * 只需要修改class的属性就能够达到最终json数据输出,不过有遇到class中 * 初始化class变量需要在构造函数中初始化的的问题。 * * 2017-8-11 深圳 龙华樟坑村 曾剑锋 ********************************************************************/ 一、参考文档: 1. getting Parse error: syntax error, unexpected T_NEW [closed] https://stackoverflow.com/questions/15806981/getting-parse-error-syntax-error-unexpected-t-new 二、测试代码: <?php class Uart { public $port = "/dev/ttyO0"; public $value = "OK"; } class Context { public $uart = new Uart();; public $version = "v0.0.1"; } $context = new Context; $context_json = json_encode($context); echo $context_json ?> 三、报错内容: Parse error: syntax error, unexpected ‘new‘ (T_NEW) in /usr/share/web/time.php on line 8 四、最终代码: <?php class Uart { public $port = "/dev/ttyO0"; public $value = "OK"; } class Context { public $uart; public $version = "v0.0.1"; public function __construct() { $this->uart = new Uart(); } } $context = new Context; $context_json = json_encode($context); echo $context_json ?> 五、输出结果: {"uart":{"port":"\/dev\/ttyO0","value":"OK"},"version":"v0.0.1"} 六、原因: you must do initialize new objects in the __construct function;
以上是关于PHP convet class to json data的主要内容,如果未能解决你的问题,请参考以下文章
Typescript JSON to Class with "es5"
项目windows运行正常,而Linux上运行报错: class path resource [kwhRules.json] cannot be resolved to absolute file
How to auto-generate a C# class file from a JSON string [closed]
ueditor百度富文本编辑器linux下报错: class path resource [config.json] cannot be resolved to absolute file path