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