千家信息网

PHP中怎么获取类和对象的属性字段

发表于:2025-02-05 作者:千家信息网编辑
千家信息网最后更新 2025年02月05日,本篇文章为大家展示了PHP中怎么获取类和对象的属性字段,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。get_class_vars获取类的公有属性及默认值(包含
千家信息网最后更新 2025年02月05日PHP中怎么获取类和对象的属性字段

本篇文章为大家展示了PHP中怎么获取类和对象的属性字段,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

get_class_vars

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

get_object_vars

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

ReflectionClass

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

实例

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

上述内容就是PHP中怎么获取类和对象的属性字段,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。

0