首先是遍历属性:
1 <?php 2 class A{ 3 public $a1 = 1; 4 protected $a2 = 2; 5 private $a3 = 3; 6 function fetchAllProp(){ 7 //遍历时,key取得属性名,value取得对应值 8 foreach($this as $key => $value){ 9 echo " "."属性: $key "; 10 } 11 } 12 13 14 } 15 $o1 = new A(); 16 $o1->fetchAllProp(); 17 18 19 ?>
结果展示:
获取对象的属性值:
1 <?php 2 class A{ 3 public $a1 = 1; 4 protected $a2 = 2; 5 private $a3 = 3; 6 function fetchAllProp(){ 7 //遍历时,key取得属性名,value取得对应值 8 foreach($this as $key => $value){ 9 echo " "."属性值: $value "; 10 } 11 } 12 13 14 } 15 $o1 = new A(); 16 $o1->fetchAllProp(); 17 18 19 ?>
上面的两段代码区别:就是那个foreach中的$key或者是$value换了,别的没啥区别,就是foreach遍历