【问题标题】:How to get all public properties of a class as json?如何将类的所有公共属性作为 json 获取?
【发布时间】:2014-03-14 16:54:58
【问题描述】:

考虑以下示例:

<?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获取?

【问题讨论】:

标签: php arrays json function oop


【解决方案1】:

您只需创建另一个类 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;

【讨论】:

  • 我不知道我的班级有什么属性,我只想把它们都打印出来
  • get_object_vars() 也将返回受保护和公共属性(如果在类范围内使用)。 OP 只询问 public
  • 这似乎是最简单的方法。非常感谢
  • 现在发布最终答案...检查一下...谢谢大家指出错误...:)
  • @mingfish_004..很高兴我能帮上忙。
【解决方案2】:
$a = array();
$reflect = new ReflectionClass($this /* $foo */);
$props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);

foreach ($props as $prop) {
    /* here you can filter for spec properties or you can do some recursion */
    $a[ $prop->getName() ] = $a[ $prop->getValue()]; 
}

return json_encode($a);

【讨论】:

  • 根据问题,这个答案可能非常准确。 ++
【解决方案3】:

由于public 成员也可以在类外访问..

访问类外的成员

$p = new p();
foreach($p as $key => $value) {
    $arr[$key]=$value;
}

Demo

通过使用ReflectionClass 访问类中的public 成员

<?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(){
        static $arr;
        $reflect = new ReflectionClass(p);
        $props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);

        foreach ($props as $prop) {
            $arr[$prop->getName()]=$prop->getValue($this); //<--- Pass $this here
        }
        return json_encode($arr);

    }
}

$p = new p();
echo $json=$p->get_p_as_json();

Demo

【讨论】:

  • get_object_vars() ?而且,OP 需要一个类范围内的方法。不在外面。
  • @HAL9000,我使用了反射。
  • 返回 {"name":null,"sex":null}
  • @mingfish_004, 修改代码和演示。忘记添加$this 关键字。现在工作正常。
【解决方案4】:

执行此操作的最好方法本身不是调用类的方法。 但是,您可以启动以下操作:

$myPublicMethodsInJson = json_encode(get_class_methods($p));

但是,您将无法从类中调用 get_class_methods,因为它将返回您的所有方法,私有和公共。当您从类外部调用它时,它只会返回公共方法。

【讨论】:

    猜你喜欢
    • 2011-01-02
    • 2010-10-23
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 2010-11-30
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多