php - 在 PHP 中将类的静态成员编码为 JSON

标签 php json oop static-members

我有以下代码。

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/

相关文章:

php - 通过查询Elasticsearch-PHP Client 2.0+更新

iphone - 解读苹果的交易收据

javascript - ng-选择 AngularJS

c++ - Qt4:访问父类的最佳方式(1级,2级......)

PHP 类实例化。使用或不使用括号?

php - 在 PHP 中将 MySQL 数据格式化到下一列的最简单方法

php - 从 Doctrine2 和 Symfony2 的集合中获取独特的属性?

php - 我只有一个字段提交到 mySQL 数据库

javascript - 如何将 json 写在单独的行上

python - self.__dict__.update(**kwargs) 风格是好还是坏?