gpt4 book ai didi

php - 如何获取一个类的所有公共(public)属性作为json?

转载 作者:可可西里 更新时间:2023-10-31 23:53:19 25 4
gpt4 key购买 nike

考虑以下示例:

<?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;

问题:如何获取一个类的所有public属性作为JSON

最佳答案

您只需创建另一个类 q 扩展自 p。然后代码如下所示:

class p {
public $name = 'jimmy';
public $sex = 'male';
private $age = 31;
// there should be more unknown 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;

关于php - 如何获取一个类的所有公共(public)属性作为json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21794449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com