文章主要介绍了PHP获取对象属性的三种方法,结合实例形式分析了php面向对象程序设计中获取对象属性的常见操作技巧,需要的朋友可以参考下。

PHP获取对象属性的三种方法,具体如下:

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

  1. class TestClass {
  2.   private $a;
  3.   protected $b;
  4.   public $c;
  5.   public $d;
  6.   public static $e;
  7.   private function funcA() {
  8.   }
  9.   protected function funcB() {
  10.   }
  11.   public function funcC() {
  12.   }
  13.   public function getPropertyMethodOne() {
  14.     echo "[get_object_vars]", PHP_EOL;
  15.     $vars = get_object_vars($this);
  16.     foreach ($vars as $k => $v) {
  17.       echo $k, ' => ', $v, PHP_EOL;
  18.     }
  19.   }
  20.   public function getPropertyMethodTwo() {
  21.     echo "[foreach object]", PHP_EOL;
  22.     foreach ($this as $k => $v) {
  23.       echo $k, ' => ', $v, PHP_EOL;
  24.     }
  25.   }
  26.   public function getPropertyMethodThree() {
  27.     echo "[reflection]", PHP_EOL;
  28.     $class = new ReflectionClass($this);
  29.     foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
  30.       if (!$property->isStatic()) {
  31.         echo $property->getName(), ' => ', $property->getValue($this), PHP_EOL;
  32.       }
  33.     }
  34.   }
  35. }

测试代码一

  1. $obj = new TestClass();
  2. echo "[get_object_vars]", PHP_EOL;
  3. $vars = get_object_vars($obj);
  4. foreach ($vars as $k => $v) {
  5.   echo $k, ' => ', $v, PHP_EOL;
  6. }
  7. echo "[foreach object]", PHP_EOL;
  8. foreach ($obj as $k => $v) {
  9.   echo $k, ' => ', $v, PHP_EOL;
  10. }
  11. echo "[reflection]", PHP_EOL;
  12. $class = new ReflectionClass($obj);
  13. foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
  14.   if (!$property->isStatic()) {
  15.     echo $property->getName(), ' => ', $property->getValue($obj), PHP_EOL;
  16.   }
  17. }

输出:

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

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

测试代码二

  1. $obj = new TestClass();
  2. $obj->getPropertyMethodOne();
  3. $obj->getPropertyMethodTwo();
  4. $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的实例属性都能获取到。反射就不用说了,通过手动筛选,各种类型的属性都能获取到。