PHP Classes and Objects
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.
Creating a 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.
?>
Activity
Try It Yourself!
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.
Quiz
Quick Quiz
- What is the difference between a class and an object in PHP?
- How do you create a constructor in a PHP class?
Answers: A class defines a blueprint, and an object is an instance of the class. You create a constructor with the __construct() method.