How to get all public properties of a class like json?

Consider the following example:

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

Question: How to get all public properties of a class like JSON?

+3
source share
4 answers

You just create another class qthat extends from p. And then the code looks like this:

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;
+6
source

Because members publiccan also be accessed outside the classroom.

Access to members outside the classroom

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

Demo

Access members publicin class usingReflectionClass

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

+5
source
$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);
+5

- , . :

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

However, you cannot call get_class_methods from the class because it will return ALL of your methods, private and public. When you call it from outside the class, it returns only public methods.

+3
source

All Articles