如何将类的所有公共属性作为json?

时间:2014-02-15 06:58:08

标签: php arrays json function oop

请考虑以下示例:

<?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;

问题: 如何将类的所有公开属性设为JSON

4 个答案:

答案 0 :(得分:6)

您只需从q创建另一个类p。然后代码如下:

class p{
    public $name = 'jimmy';
    public $sex = 'male';
    private $age = 31;
    // there should be more unknow 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;

答案 1 :(得分:5)

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

访问班级以外的成员

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

Demo

使用public

访问班级中的ReflectionClass成员
<?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

答案 2 :(得分:5)

$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 :(得分:3)

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

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

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

相关问题