Google News
logo
PHP program to create multiple objects of a class and access attributes of the class
In the following example of PHP program that creates multiple objects of a class and access attributes of the class :
Program :
<?php

class Person {
  public $name;
  public $age;

  function __construct($name, $age) {
    $this->name = $name;
    $this->age = $age;
  }

  function getDetails() {
    return "Name: " . $this->name . ", Age: " . $this->age;
  }
}

// Creating objects of the Person class
$person1 = new Person("John", 30);
$person2 = new Person("Mary", 25);
$person3 = new Person("Bob", 40);

// Accessing attributes of the objects
echo $person1->getDetails() . "\n";
echo $person2->getDetails() . "\n";
echo $person3->getDetails() . "\n";
?>
Output :
Name: John, Age: 30
Name: Mary, Age: 25
Name: Bob, Age: 40
This program creates an object of the `Person` class, which has two attributes: `name` and `age`. The `__construct()` method is used to set the values of these attributes when an object is created. The `getDetails()` method is used to get the details of the person.

Three objects of the `Person` class are created and their attributes are accessed using the `getDetails()` method.