将 class 的静态成员编码为 PHP 中的 JSON
Encoding static member of class as JSON in PHP
我有如下一段代码。
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 class 属性 和成员编码为 JSON 对象。我的问题是 json_encode()
忽略 public static $one = 1;
结果将是:
{
"three": 3
}
虽然我希望它也打印 public 静态成员,例如:
{
"one": 1,
"three": 3
}
JSON编码可以用PHP中的静态成员完成吗?
根据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}
在本机实现中:NO.
如果你使用 Php v >= 5.4.0,你可以使用 JsonSerializable
示例如下:
class myClass implements JsonSerializable
{
private $_name = 'test_name';
public $email = 'test@mail.com';
public static $staticVar = 5;
public function jsonSerialize()
{
return get_class_vars(get_class($this));
}
}
echo json_encode(new myClass());
我有如下一段代码。
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 class 属性 和成员编码为 JSON 对象。我的问题是 json_encode()
忽略 public static $one = 1;
结果将是:
{
"three": 3
}
虽然我希望它也打印 public 静态成员,例如:
{
"one": 1,
"three": 3
}
JSON编码可以用PHP中的静态成员完成吗?
根据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}
在本机实现中:NO.
如果你使用 Php v >= 5.4.0,你可以使用 JsonSerializable
示例如下:
class myClass implements JsonSerializable
{
private $_name = 'test_name';
public $email = 'test@mail.com';
public static $staticVar = 5;
public function jsonSerialize()
{
return get_class_vars(get_class($this));
}
}
echo json_encode(new myClass());