php – 如何将类的所有公共属性作为json?
发布时间:2020-12-13 22:14:56 所属栏目:PHP教程 来源:网络整理
导读:考虑以下示例: ?phpclass p{ public $name = 'jimmy'; public $sex = 'male'; private $age = 31; // there should be more unknow properties here .. function test(){ echo $this-name; } function get_p_as_json(){ // how can i get json of this clas
考虑以下示例:
<?php class p{ public $name = 'jimmy'; public $sex = 'male'; private $age = 31; // there should be more unknow properties here .. function test(){ echo $this->name; } function get_p_as_json(){ // how can i get json of this class which contains only public properties ? // {"name":"jimmy","sex":"male"} } } $p = new p(); $json = $p->get_p_as_json(); echo $json; 问题:如何将类的所有公共属性作为JSON? 解决方法
你只需要从p创建另一个类q.然后代码如下所示:
class p{ public $name = 'jimmy'; public $sex = 'male'; private $age = 31; // there should be more unknow properties here .. function test(){ echo $this->name; } } class q extends p{ function get_p_as_json($p){ return json_encode(get_object_vars($p)); } } $q = new q(); $p = new p(); $json = $q->get_p_as_json($p); echo $json; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |