Google News
logo
PHP program to create an object of a class and access the class attributes
In the following example of PHP program that demonstrates how to create an object of a class and access its attributes :
Program :
<?php
// Define a class
class Car {
  // Define attributes
  public $make;
  public $model;
  public $year;

  // Define constructor method
  function __construct($make, $model, $year) {
    $this->make = $make;
    $this->model = $model;
    $this->year = $year;
  }
}

// Create an object of the Car class
$my_car = new Car("Honda", "Civic", 2021);

// Access the attributes of the object
echo "Make: " . $my_car->make . "<br>";
echo "Model: " . $my_car->model . "<br>";
echo "Year: " . $my_car->year . "<br>";
?>
Output :
Make: Honda
Model: Civic
Year: 2021
This program defines a `Car` class with three attributes (`make`, `model`, and `year`) and a constructor method that initializes these attributes.

It then creates an object of the `Car` class using the `new` keyword and passing in values for the `make`, `model`, and `year` attributes.

Finally, it accesses the attributes of the object using the `->` operator and prints their values to the screen.