class Article {
private $id;
private $title;
public $content;
function __construct($id,$title,$content)
{
$this->id = $id;
$this->title = $title;
$this->content = $content;
}
}
$foo = new Article(1,"反射獲取私有成員","獲取成員");
$reflect = new ReflectionClass($foo);
$props = $reflect->getProperties();//ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED
foreach ($props as $prop) {
$prop->setAccessible(true);//不使用setAccessible
則會報錯(PHP Fatal error: Uncaught exception 'ReflectionException' with message 'Cannot access non-public member)
print $prop->getName() . "\t";
print $prop->getValue($foo)."\n";
}
class Article { private $id; private $user; private $title; public $content; function __construct($id, User $user, $title, $content) { $this->id = $id; $this->user = $user; $this->title = $title; $this->content = $content; } } class User { private $id; private $username; public function __construct($id, $username) { $this->id = $id; $this->username = $username; } } function obj_to_array_demo($obj) { $reflect = new ReflectionClass($obj); $props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED); $array = []; foreach ($props as $prop) { $prop->setAccessible(true); $key = $prop->getName(); $value = $prop->getValue($obj); if (is_object($value)) { $value = obj_to_array_demo($value); } $array[$key] = $value; } return $array; } $user = new User(1, "setevn"); $foo = new Article(1, $user, "反射獲取私有成員","獲取成員"); var_export(obj_to_array_demo($foo));
array ( 'id' => 1, 'user' => array ( 'id' => 1, 'username' => 'setevn', ), 'title' => '反射獲取私有成員', 'content' => '獲取成員', )
封裝成工具
/** * 針對成員都是私有屬性的對象 * @param $obj * @param bool $removeNull 干掉空值 * * @return array */ public static function Obj2Array($obj, $removeNull=true) { $reflect = new \ReflectionClass($obj); $props = $reflect->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PRIVATE | \ReflectionProperty::IS_PROTECTED); $array = []; foreach ($props as $prop) { $prop->setAccessible(true); $key = $prop->getName(); $value = $prop->getValue($obj); if ($removeNull == true && $value === null) { continue; } if (is_object($value)) { $value = self::Obj2Array($value); } $array[$key] = $value; } return $array; }