PHP 通过反射获取到私有成员


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM