OOP Concepts

Object-Oriented Programming

PHP is a server-side scripting language, which can be used for web development. It also has the capabilities to be a fully object-oriented language. Here is how you can declare a class and instantiate an object:

Class Definition

In PHP, a class is defined using the class keyword, followed by a name of the class:

<?php
class Car {
    function Car() {
        $this->model = "VW";
    }
}

// create an object
$herbie = new Car();

// show object properties
echo $herbie->model;
?>

Properties and Methods

A class can contain its own properties and methods:

<?php
class Car {
    public $color; // property
    public $model; // property
    public function display() {  // method
        return "I am a " . $this->color . " " . $this->model . ".";
    }
}

$car1 = new Car();
$car1->color = "blue";
$car1->model = "VW";
echo $car1->display();
?>

Inheritance

In PHP, it is possible for a class to inherit the properties and methods of another class. This is called inheritance. Here is an example:

<?php
class Car {
    public $color;
    public $model;
    public function __construct($color, $model) {
        $this->color = $color;
        $this->model = $model;
    }
    public function message() {
        return "Am I a car? Yes.";
    }
}

class SportsCar extends Car {
    public function message() {
        return "Am I a sportscar? Yes.";
    }
}

$sportscar = new SportsCar("red", "Ferrari");
echo $sportscar->message();
echo $sportscar->color;
echo $sportscar->model;
?>

Object-Oriented Programming (OOP) is a way to manage and organize your code. It helps you to keep related things together and is great for larger applications.

Last updated