Home >Backend Development >PHP Tutorial >PHP object-oriented-code sharing for object traversal
The traversal of objects is the same as the traversal of arrays. The traversal of objects refers to the traversal of instanceproperties.
The attributes traversed below are "accessible attributes" in this scope (access permissions must be considered).
<?phpclass A{ public $p1 = 1; protected $p2 = 2; private $p3 = 3; static $p4 = 4; }$obj1 = new A();foreach($obj1 as $key => $value){//$key表示对象的属性,$value是其对应的值 echo "<br />属性$key :" . $value; }?>
Run result:
属性p1 :1
It can be seen that only public modified properties can be traversed, so how to traverse all properties of an object? Just write a traversal method inside the class.
<?phpclass A{ public $p1 = 1; protected $p2 = 2; private $p3 = 3; static $p4 = 4; //静态属性 function showAllProperties(){ foreach($this as $key => $value){ echo "<br />属性$key :$value"; } } }$obj1 = new A();$obj1->showAllProperties();?>
Run result:
属性p1 :1 属性p2 :2 属性p3 :3
But static properties do not belong to the object, so they cannot be traversed.
The above is the detailed content of PHP object-oriented-code sharing for object traversal. For more information, please follow other related articles on the PHP Chinese website!