Posted in PHP onJanuary 03, 2019
本文实例讲述了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获取对象属性的三种方法实例分析
- Author -
chunyuan314声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@