How to loop through an object’s properties

The syntax

foreach($objectName as [ $propertyName => ] $propertyValue) {
  // statements to execute 
}

Define an Employee class

class Employee {
  public $firstName, $lastName; 
  private $ssn, $dob;
  public function __construct($first, $last) { 
    $this->firstName = $first; 
    $this->lastName = $last; 
  } 
        
  // getSSN, setSSN, getDOB, setDOB methods not shown 
        
  // Show all properties – private, protected, and public public 
  function showAll() { 
    echo("<ul>\n");
    foreach($this as $name => $value ) {
      echo("<li>$name = $value</li>\n");
    }
    echo("</ul>\n");
  } 
}

Create an Employee object with four properties

$employee = new Employee('John', 'Doe'); 
$employee->setSSN('999-14-3456'); 
$employee->setDOB('3-15-1970');

Show all properties

$employee->showAll();

Show public properties only

echo("<ul>\n");
foreach($employee as $name => $value ) { 
  echo("<li>$name = $value</li>\n");
}
echo("</ul>\n");

Description

Back