首页 > 代码库 > PHP convet class to json data

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 = http://www.mamicode.com/"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 = http://www.mamicode.com/"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