我有以下代码。
class SomeClass
{
public static $one = 1;
private static $two = 2;
public $three = 3;
private $four = 4;
}
header("Content-Type: application/json");
echo json_encode(new SomeClass());
我想要实现的是将公共(public)类属性和成员编码为 JSON 对象。我的问题是 json_encode()
忽略 public static $one = 1;
结果将是:
{
"three": 3
}
虽然我希望它也打印公共(public)静态成员,例如:
{
"one": 1,
"three": 3
}
PHP 中的静态成员可以进行 JSON 编码吗?
最佳答案
根据PHP manual :
Static properties cannot be accessed through the object using the arrow operator ->.
这意味着不
尽管如此,我还是利用 Reflections 提出了解决方案:
class SomeClass
{
public static $one = 1;
private static $two = 2;
public $three = 3;
private $four = 4;
}
$reflection = new ReflectionClass('SomeClass');
$instance = $reflection->newInstance();
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
$jsonArray = array();
foreach($properties as $property) {
$jsonArray[$property->getName()] = $property->getValue($instance);
}
echo json_encode($jsonArray);
结果是
{"one":1,"three":3}
关于php - 在 PHP 中将类的静态成员编码为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35225003/