php 获得类所有属性值_PHP 获取类 / 对象的属性字段及属性值

get_class_vars

获取类的公有属性及默认值(包含公有的静态属性),用来列举类的公有属性字段。

get_object_vars

获取对象的公有属性及属性值(不包含公有的静态属性)。

ReflectionClass

如果想要获取对象的各类属性(public/protected/private | static),就需要借助强大的反射类来完成了。 PHP 提供了 \ReflectionClass::class 可以帮助我们解析类的实例对象,通过 \ReflectionClass::getProperties方法获取对象所有的属性值。

实例<?php

class Foo

{

// 类常量

const CLASS_NAME = "Foo";

// 成员属性

public $name;

protected $sex = "female";

private $age;

// 类静态属性

// php 的对象是可以访问类的 static 属性的

// 但应该使用类的方式访问更为规范

// const 属性只能通过类的方式访问

public static $bar = "bar";

public function __construct($name, $sex, $age)

{

$this->name = $name;

$this->sex = $sex;

$this->age = $age;

}

/**

* 获取对象的属性字段及属性值

* @param [type] $property_scope 属性域

* @param boolean $static_excluded 是否包含静态属性

* @return array

* @throws \ReflectionException|\Exception

*/

public function getProperties($property_scope = null, $static_excluded = false)

{

// 校验反射域是否合法

if (isset($property_scope) && !in_array($property_scope, [

\ReflectionProperty::IS_STATIC,

\ReflectionProperty::IS_PUBLIC,

\ReflectionProperty::IS_PROTECTED,

\ReflectionProperty::IS_PRIVATE,

])) {

throw new Exception("reflection class property scope illegal!");

}

$properties_mapping = [];

// 谈判官

$classRef = new \ReflectionClass($this);

$properties = isset($property_scope) ? $classRef->getProperties($property_scope) : $classRef->getProperties();

foreach ($properties as $property) {

// 为了兼容反射私有属性

$property->setAccessible(true);

// 当不想获取静态属性时

if ($property->isStatic() && $static_excluded) {

continue;

}

// 将得到的类属性同具体的实例绑定解析,获得实例上的属性值

$properties_mapping[$property->getName()] = $property->getValue($this);

}

return $properties_mapping;

}

}

$foo = new Foo("big_cat", "male", 29);

// 获取类的公有属性及默认值(包含静态属性)

var_dump(get_class_vars(get_class($foo)));

// 获取对象的公有属性及值(不包含类静态属性)

var_dump(get_object_vars($foo));

// 获取对象的静态属性

var_dump($foo->getProperties(\ReflectionProperty::IS_STATIC));

// 获取对象的公有属性 并排除静态属性

var_dump($foo->getProperties(\ReflectionProperty::IS_PUBLIC, true));

// 获取对象的保护属性

var_dump($foo->getProperties(\ReflectionProperty::IS_PROTECTED));

// 获取对象的私有属性

var_dump($foo->getProperties(\ReflectionProperty::IS_PRIVATE));

其他参考/**

* 获取类的常量属性

* @see https://www.php.net/manual/en/reflectionclass.getconstants.php

*/

\ReflectionClass::getConstants()

/**

* 获取类的方法

* @see https://www.php.net/manual/en/reflectionclass.getmethods.php

*/

\ReflectionClass::getMethods()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值