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;
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);
}
return json_encode($arr);
}
}
$p = new p();
echo $json=$p->get_p_as_json();
Demo
source
share