dongshanxiao7328 2016-02-05 13:05
浏览 25
已采纳

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

I have the following piece of code.

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());

What I want to achieve is encode the public class property and member as a JSON object. My problem is that json_encode() ignores public static $one = 1; and the result will be:

{
    "three": ​3
}

Although I expect it to print the public static member as well, such as:

{
    "one": 1,
    "three": ​3
}

Can JSON encoding be done with static members in PHP?

  • 写回答

2条回答 默认 最新

  • dongxiaoxing3058 2016-02-05 13:11
    关注

    According to PHP manual:

    Static properties cannot be accessed through the object using the arrow operator ->.

    That means no

    Nevertheless, I came up with the solution utilizing 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);
    

    The result is

    {"one":1,"three":3}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)