Certainly! Here's a simple example to illustrate PHP Object-Oriented Programming (OOP). We'll create a Car class with properties and methods, and then instantiate it to create a car object.
<?php
// Define the 'Car' class
class Car {
// Declare properties
public $make;
public $model;
public $color;
private $running = false;
// Constructor method
public function __construct($make, $model, $color) {
$this->make = $make;
$this->model = $model;
$this->color = $color;
}
// Method to start the car
public function start() {
$this->running = true;
echo "The $this->make $this->model has started.\n";
}
// Method to stop the car
public function stop() {
$this->running = false;
echo "The $this->make $this->model has stopped.\n";
}
// Method to check if the car is running
public function isRunning() {
return $this->running;
}
// Destructor method
public function __destruct() {
echo "The $this->make $this->model is being destroyed.\n";
}
}
// Create car objects
$car1 = new Car("Toyota", "Corolla", "Red");
$car2 = new Car("Honda", "Civic", "Blue");
// Call methods on the car objects
$car1->start();
echo $car1->isRunning() ? "Car is running\n" : "Car is not running\n";
$car2->start();
$car2->stop();
echo $car2->isRunning() ? "Car is running\n" : "Car is not running\n";
?>
In this example:
- We define a
Car class with properties for make, model, and color.
- The
running property is private, meaning it can only be accessed from within the class methods.
- A constructor
__construct() initializes the object properties when a new object is created.
- The
start(), stop(), and isRunning() methods are actions that can be performed on a car object.
- The destructor method
__destruct() is called automatically when an object is destroyed or the script ends. It's not needed in simple examples but can be useful for cleanup operations.
- We create two car objects (
$car1 and $car2) with different attributes using the new keyword.
- We call the methods to start and stop the cars and check whether they are running.
When you run this script on a server with PHP installed, or a development environment, it will output the start and stop actions:
The Toyota Corolla has started.
Car is running
The Honda Civic has started.
The Honda Civic has stopped.
Car is not running
The Toyota Corolla is being destroyed.
The Honda Civic is being destroyed.
Destructor output may occur at the end of the script execution. The order might vary based on when the objects are destructed by PHP's garbage collector.