PHP OOP Introduction
In this page:
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
class Car {
public $color = "red";
function drive() {
echo "Driving a $this->color car";
}
}
$car = new Car();
$car->drive();
?>
Login to try C/C++/Java/PHP code in the editor
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
class Car {
public $color;
}
$myCar = new Car();
$myCar->color = "blue";
echo $myCar->color;
?>
Login to try C/C++/Java/PHP code in the editor
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
class Product {
public $name;
}
$p = new Product();
$p->name = "Laptop";
echo $p->name;
?>
Login to try C/C++/Java/PHP code in the editor
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
class Product {
public $name;
public $price;
}
$p1 = new Product();
$p1->name = "Laptop";
$p2 = new Product();
$p2->name = "Phone";
echo $p1->name . " / " . $p2->name;
?>
Login to try C/C++/Java/PHP code in the editor
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
class Product {
public $name = "Book";
function describe() {
echo "This product is: " . $this->name;
}
}
$p = new Product();
$p->describe();
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: