← Back to PHP Course | Chapter 8: OOP | Lesson 1 of 14

PHP OOP Introduction

What is Object-Oriented Programming?

Object-oriented programming organizes code around objects that bundle data (properties) and behavior (methods) together, instead of scattering related variables and functions loosely across a script.

Example: What is Object-Oriented Programming?

php
<?php
class Car {
    public $color = "red";
    function drive() {
        echo "Driving a $this->color car";
    }
}
$car = new Car();
$car->drive();
?>

Benefits of OOP

A class is a blueprint that defines what properties and methods its objects will have, while an object is one concrete instance created from that blueprint — much like a house blueprint versus an actual house built from it.

Example: Benefits of OOP

php
<?php
class Car {
    public $color;
}
$myCar = new Car();
$myCar->color = "blue";
echo $myCar->color;
?>

Classes vs Objects

PHP has supported OOP since PHP 4 and expanded it heavily in PHP 5 and later, so modern PHP frameworks like Laravel and Symfony are built almost entirely around classes, objects, and the patterns that come with them.

Example: Classes vs Objects

php
<?php
class Product {
    public $name;
}
$p = new Product();
$p->name = "Laptop";
echo $p->name;
?>

Properties in OOP

OOP encourages reusability and organization: once you define a Product class, you can create as many product objects as you need, each with its own data but sharing the same behavior defined once in the class.

Example: Properties in OOP

php
<?php
class Product {
    public $name;
    public $price;
}
$p1 = new Product();
$p1->name = "Laptop";
$p2 = new Product();
$p2->name = "Phone";
echo $p1->name . " / " . $p2->name;
?>

Methods in OOP

The core OOP pillars — encapsulation, inheritance, polymorphism, and abstraction — each solve a different organizational problem, and later sections in this course build up each one individually with concrete PHP examples.

Example: Methods in OOP

php
<?php
class Product {
    public $name = "Book";
    function describe() {
        echo "This product is: " . $this->name;
    }
}
$p = new Product();
$p->describe();
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.