PHP PHP 获取类 / 对象的属性字段及属性值

thorpe · 2019-12-25 10:21:12 · 热度: 307

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()

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册