Example of traversal operation of objects in PHP object oriented programming

  • 2021-12-12 03:53:14
  • OfStack

In this paper, an example is given to describe the traversal operation of objects in PHP object-oriented programming. Share it for your reference, as follows:

Object traversal and array traversal, object traversal refers to the traversal of instance attributes.

The attributes traversed below are "accessible attributes" in this scope (considering access permissions).


<?php
class A{
  public $p1 = 1;
  protected $p2 = 2;
  private $p3 = 3;
  static $p4 = 4;
}
$obj1 = new A();
foreach($obj1 as $key => $value){//$key Represents the properties of an object, $value Is its corresponding value 
  echo "<br /> Attribute $key  : " . $value;
}
?>

Run results:

Attribute p1: 1

It can be seen that only public Modified attributes can be traversed, so how can all attributes of an object be traversed? Write a traversal method inside the class.


<?php
class A{
  public $p1 = 1;
  protected $p2 = 2;
  private $p3 = 3;
  static $p4 = 4;  // Static attribute 
  function showAllProperties(){
    foreach($this as $key => $value){
      echo "<br /> Attribute $key  : $value";
    }
  }
}
$obj1 = new A();
$obj1->showAllProperties();
?>

Run results:

Attribute p1: 1
Attribute p2: 2
Attribute p3: 3

However, static attributes are not objects, so they cannot be traversed.

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: