PHP Objects And OOP

PHP Code Snippets OOP and Objects
Share:

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>";

////////////////////////////////////////////////////////////////////////////

Resulting Output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger