In object-oriented programming (OOP) in PHP, classes and objects are the building blocks. A class defines a blueprint, and an object is an instance of that class.
To create a class in PHP, use the class
keyword:
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function getDetails() {
return "This car is a $this->color $this->model.";
}
}
$myCar = new Car("Red", "Toyota");
echo $myCar->getDetails(); // Outputs: This car is a Red Toyota.
?>
Write a class for a Person
that stores their name and age. Create an object of the class and display the person's name and age.
Answers: A class defines a blueprint, and an object is an instance of the class. You create a constructor with the __construct()
method.