About
In this code snippet, we’ll take a look at objects and basic of object oriented programming in PHP.
I will just show how to make and use classes, interfaces, properties, … in PHP. I won’t go into OOP too much as I already did some other posts about that.
Let’s see the example code below.
Code:
<?php //Code///////////////////////////////////////////////////////////////////// //Interface implementation in PHP. interface IDrivable{ public function drive($destination); } //Abstract class implementation in PHP. abstract class Vehicle { //Force child class to make it's own implementation of this function. abstract protected function FillUpTank($fuel); //Child class will inherit this function and properties. //Properties. public $Mileage; public $Year; public $Model; public function GetCarStats(){ echo "Mileage: " . $this->Mileage . " Year: " . $this->Year . " Model: " . $this->Model; } } //Class implementation in PHP. class Car extends Vehicle implements IDrivable{ //Constructor function __construct($mileage, $year, $model){ //When referencing class mambers inside their class $this-> must be put infront. $this->Mileage = $mileage; $this->Year = $year; $this->Model = $model; } public $Fuel; //Implement FillUpTank from Vehicle. function FillUpTank($fuel){ $this->Fuel += $fuel; } //Implement drive() from IDrivable interface. public function drive($destination){ echo "Driving to " . $destination; } //Static class members don't need the class to be instantiated to be used. public static $VehicleType = "road vehicle"; public static function GetVehicleType(){ return Car::$VehicleType; } } //////////////////////////////////////////////////////////////////////////// //Entry point///////////////////////////////////////////////////////////// //More about OOP in PHP: https://www.php.net/manual/en/language.oop5.php echo Car::GetVehicleType();//:: is used to access static class members. echo "<br>"; //Make new instance of Car. $car = new Car(100000, 2010, "Some model..."); echo $car->Model; echo "<br>"; $car->drive("somewhere..."); echo "<br>"; $car->GetCarStats(); echo "<br>"; ////////////////////////////////////////////////////////////////////////////