PHP Classes
In PHP, a Class is a blueprint or template for creating objects. It encapsulates data (properties) and behavior (methods) into a single entity.
If a class is the architectural blueprint, an object is the actual house built from it.
1. Defining a Class
A class is defined using the class keyword.
class Car {
// Properties and Methods go here
}
2. Properties
Properties are variables that belong to a class. They represent the state or attributes of an object.
class Car {
public $color;
public $model;
}
3. Methods
Methods are functions defined inside a class. They define what an object can do.
class Car {
public $color;
public function drive() {
return "The " . $this->color . " car is driving.";
}
}
4. Objects (Instantiation)
To use a class, you create an instance of it, known as an object, using the new keyword.
$myCar = new Car();
$myCar->color = "Red";
echo $myCar->drive(); // Outputs: The Red car is driving.
5. Visibility
- Public: Accessible from anywhere.
- Private: Accessible only within the class itself.
- Protected: Accessible within the class and its child classes.
6. Constructors
A constructor is a special method that is automatically called when an object is created. It is often used to initialize properties.
class Car {
public $color;
public function __construct($color) {
$this->color = $color;
}
}
$myCar = new Car("Blue");