PHP获取对象属性的三种方法实例分析

今天查看yii源码,发现yii\base\Model中的attribute()方法是通过反射获取对象的public non-static属性。记得以前看到的代码都是用get_object_vars()这个函数获取的,昨天查看php文档,发现还可以用foreach遍历对象属性。于是写个例子练习下。

class TestClass { private $a; protected $b; public $c; public $d; public static $e; private function funcA() { } protected function funcB() { } public function funcC() { } public function getPropertyMethodOne() { echo "[get_object_vars]", PHP_EOL; $vars = get_object_vars($this); foreach ($vars as $k => $v) { echo $k, ' => ', $v, PHP_EOL; } } public function getPropertyMethodTwo() { echo "[foreach object]", PHP_EOL; foreach ($this as $k => $v) { echo $k, ' => ', $v, PHP_EOL; } } public function getPropertyMethodThree() { echo "[reflection]", PHP_EOL; $class = new ReflectionClass($this); foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { if (!$property->isStatic()) { echo $property->getName(), ' => ', $property->getValue($this), PHP_EOL; } } } }

测试代码一

$obj = new TestClass(); echo "[get_object_vars]", PHP_EOL; $vars = get_object_vars($obj); foreach ($vars as $k => $v) { echo $k, ' => ', $v, PHP_EOL; } echo "[foreach object]", PHP_EOL; foreach ($obj as $k => $v) { echo $k, ' => ', $v, PHP_EOL; } echo "[reflection]", PHP_EOL; $class = new ReflectionClass($obj); foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { if (!$property->isStatic()) { echo $property->getName(), ' => ', $property->getValue($obj), PHP_EOL; } }

输出:

[get_object_vars]
c =>
d =>
[foreach object]
c =>
d =>
[reflection]
c =>
d =>

可见,当着三种方法用在类的外部时,结果是一样的。get_object_vars()和foreach是获取到的是对象的public non-static属性,而通过反射的话则需要手动筛选出public non-static属性。

测试代码二

$obj = new TestClass(); $obj->getPropertyMethodOne(); $obj->getPropertyMethodTwo(); $obj->getPropertyMethodThree();

输出

[get_object_vars]
a =>
b =>
c =>
d =>
[foreach object]
a =>
b =>
c =>
d =>
[reflection]
c =>
d =>

可见,get_object_vars()和foreach用在类内部时,private、protected、public的实例属性都能获取到。反射就不用说了,通过手动筛选,各种类型的属性都能获取到。

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/f751ac7e11f8f52d7ad9dc0d5d0a9e21.html