Hereβs the full example:
<?php
// π A class is a blueprint for creating objects (instances).
class Helicopter
{
/* ---------------------------------
* π·οΈ PROPERTIES (variables that belong to the class)
* --------------------------------- */
// A constant value that never changes
public const TYPE = "Utility Helicopter";
// Public property β accessible from anywhere
public $model;
// Protected property β accessible only inside this class and child classes
protected $maxSpeed;
// Private property β accessible only inside this class
private $engineStarted = false;
// Static property β belongs to the class, not to objects
public static $electricity = true;
/* ---------------------------------
* ποΈ CONSTRUCTOR
* --------------------------------- */
// Constructor runs automatically when you create an object
public function __construct($model, $maxSpeed)
{
$this->model = $model;
$this->maxSpeed = $maxSpeed;
echo "Helicopter {$this->model} created with max speed of {$this->maxSpeed} km/h.\n";
}
/* ---------------------------------
* βοΈ INSTANCE METHODS
* --------------------------------- */
// Normal method that works with the object (needs $this)
public function startEngine()
{
$this->engineStarted = true;
echo "Engine started for {$this->model}.\n";
}
// Another instance method
public function fly()
{
if ($this->engineStarted) {
echo "{$this->model} is flying at {$this->maxSpeed} km/h.\n";
} else {
echo "Start the engine first!\n";
}
}
// Getter method for a private property
public function isEngineStarted()
{
return $this->engineStarted;
}
/* ---------------------------------
* π°οΈ STATIC METHODS
* --------------------------------- */
// Static method belongs to the class, not objects
public static function checkElectricity()
{
if (self::$electricity) {
echo "Electric systems are powered.\n";
} else {
echo "No electricity available.\n";
}
}
}
/* ---------------------------------
* π USING THE CLASS
* --------------------------------- */
// Create an object (instance) of Helicopter
$hely = new Helicopter("Apache", 300);
// Call instance methods
$hely->startEngine();
$hely->fly();
// Call static method (without creating an object)
Helicopter::checkElectricity();
// Accessing a constant
echo "This is a " . Helicopter::TYPE . "\n";
Explanation of important pieces
public $model;β properties are like variables, but tied to the object.__construct()β constructor, runs whennew Helicopter(...)is called.$this->...β refers to the current object.private $engineStarted;β encapsulation: outside code canβt change it directly.public function fly()β normal method, uses instance data.public static function checkElectricity()β class-level method, doesnβt need an object.self::TYPE/Helicopter::checkElectricity()β use::for constants and static methods.