☜
☞
Class
Creating a class in PHP is straightforward. PHP is an object-oriented programming language, so it supports classes and objects. Below is an example of how you can define and use a class in PHP.
Defining a Class
<?php
class Car {
// Properties
public $make;
public $model;
public $year;
// Constructor
public function __construct($make, $model, $year) {
$this->make = $make;
$this->model = $model;
$this->year = $year;
}
// Methods
public function display() {
return "This car is a $this->year $this->make $this->model.";
}
}
// Create an instance of the class
$myCar = new Car("Toyota", "Corolla", 2021);
// Access the method
echo $myCar->display(); // Outputs: This car is a 2021 Toyota Corolla.
?>
Explanation
Class Definition:
- class Car { ... } defines a class named Car.
- Properties ($make, $model, $year) are defined within the class.
Constructor:
- The __construct method is a special method called a constructor. It initializes the object when it is created.
- The constructor takes three parameters ($make, $model, $year) and assigns them to the corresponding properties of the class.
Methods:
- display() is a method of the class that returns a string describing the car.
Creating an Instance:
- $myCar = new Car("Toyota", "Corolla", 2021); creates an instance of the Car class.
Accessing Methods:
- echo $myCar->display(); calls the display method of the $myCar object and prints the result.
Adding More Features
You can add more methods and properties as needed. For example, you can add a method to start the car:
<?php
class Car {
// Properties
public $make;
public $model;
public $year;
public $isRunning = false;
// Constructor
public function __construct($make, $model, $year) {
$this->make = $make;
$this->model = $model;
$this->year = $year;
}
// Methods
public function display() {
return "This car is a $this->year $this->make $this->model.";
}
public function start() {
$this->isRunning = true;
return "The car has started.";
}
}
// Create an instance of the class
$myCar = new Car("Toyota", "Corolla", 2021);
// Access the method
echo $myCar->display(); // Outputs: This car is a 2021 Toyota Corolla.
echo $myCar->start(); // Outputs: The car has started.
?>
Summary
- Class: Defines a blueprint for objects.
- Properties: Variables within a class.
- Methods: Functions within a class.
- Constructor: Special method to initialize objects.
- Instance: An individual object created from a class.
Feel free to ask if you have any more specific requirements or questions!
☜
☞