获取类的公有属性及默认值(包含公有的静态属性),用来列举类的公有属性字段。php
获取对象的公有属性及属性值(不包含公有的静态属性)。app
若是想要获取对象的各种属性(public/protected/private | static),就须要借助强大的反射类来完成了。 PHP
提供了 \ReflectionClass::class
能够帮助咱们解析类的实例对象,经过 \ReflectionClass::getProperties
方法获取对象全部的属性值。this
<?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()