As your applications grow in complexity, writing code sequentially or relying purely on standard functions can become difficult to manage. This is where Object-Oriented Programming (OOP) comes in.
A Class is a blueprint or template for creating Objects. If a class is the blueprint for a house, the object is the actual physical house built from that blueprint.
Variables defined inside a class are called Properties. They represent the state or the data that an object holds.
In modern PHP, it is highly recommended to explicitly declare the type for every property (e.g., string, int, float). This enforces strict data integrity, preventing a string from accidentally being saved into a property meant for a number.
Once an object has been instantiated from a class, you can assign values to its public properties (setting) or retrieve those values to use elsewhere in your code (getting) by using the -> (object operator).
<?php
class Book
{
public string $title;
public int $pages;
}
$myBook = new Book();
// Setting property values
$myBook->title = "The Great Gatsby";
$myBook->pages = 180;
// Getting property values
echo $myBook->title; // Outputs: The Great Gatsby
echo $myBook->pages; // Outputs: 180
You must also declare the visibility of a property, which dictates the scope—meaning where in your application that property is allowed to be read or modified. PHP provides three visibility modifiers:
If you attempt to access a private or protected property from outside the class scope (the global script), PHP will immediately halt execution and throw a fatal error.
Example Think of a smart lock on a house. The brand name of the lock is written right on the front for everyone to see (Public). However, the master PIN code used to configure the lock is hidden deep inside the lock's internal memory chip (Private).
<?php
class SmartLock
{
public string $brandName; // Public: anyone can see this from the outside
private int $masterPin; // Private: hidden inside the machine
}
$myLock = new SmartLock();
// Because it is public, we can read and write to it from anywhere.
$myLock->brandName = "Yale";
echo $myLock->brandName; // Outputs: Yale
// This fails because the outside script is trying to force its way into
// a private property from outside the class boundaries.
$myLock->masterPin = 1234;
// ERROR: Cannot access private property SmartLock::$masterPin
Functions defined inside a class are called Methods. While properties represent what an object knows (its data), methods represent what an object can do (its behavior).
Methods are used to manipulate an object's internal properties, perform calculations, or execute tasks related to that specific object.
Methods are written just like regular functions, but they live inside a class. They default to public visibility if you don't specify one, though it is best practice to always explicitly declare it.
To call an object's method from your main script, you use the -> (object operator) followed by the method name and parentheses ().
<?php
class Speaker
{
public function announce(): void
{
echo "Attention everyone! The event is starting.";
}
}
$mySpeaker = new Speaker();
$mySpeaker->announce(); // Outputs: Attention everyone! The event is starting.
To actually use the Car class, you need to create an object from it. This process is called instantiation, and it is done using the new keyword.
Once you have an object, you access its properties and methods using the -> (object operator).
<?php
$myCar = new Car();
// Setting properties
$myCar->make = "Toyota";
$myCar->model = "Corolla";
// Calling a method
$myCar->startEngine(); // Outputs: Vroom! The engine is running.
$this KeywordWhen you are writing code inside a class's method, you often need to refer to the object's own properties. You do this using the $this keyword, which literally means "this current object."
<?php
class User
{
public $name;
public function greet()
{
// Use $this to access the name property of this specific user
echo "Hello, my name is " . $this->name;
}
}
$user1 = new User();
$user1->name = "Alice";
$user1->greet(); // Outputs: Hello, my name is Alice
A constructor is a special "magic" method named __construct() that is automatically executed the exact moment an object is created from a class. Constructors are perfect for setting up initial property values or requiring parameters before an object can exist.
<?php
class Product
{
public $title;
public $price;
// This runs immediately when 'new Product()' is called
public function __construct($title, $price)
{
$this->title = $title;
$this->price = $price;
}
public function display()
{
echo $this->title . " costs $" . $this->price;
}
}
// We must now pass the arguments directly when creating the object
$laptop = new Product("Laptop", 999.99);
$laptop->display(); // Outputs: Laptop costs $999.99
In modern PHP, there is a fantastic shortcut to creating and assigning properties at construction, called Constructor Property Promotion.
This feature allows you to combine property declarations, constructor parameters, and variable assignments into one single line of code.
By adding a visibility modifier (public, private, or protected) directly to the arguments inside the constructor's parentheses (), PHP understands that you want to automatically create that property and assign the incoming value to it.
Because PHP does all of this heavy lifting for you, the body of your constructor method can be left completely empty.
<?php
class ModernProduct
{
public function __construct(
public string $sku,
public float $price,
) {
}
// Instantiating the class and passing the arguments
$product = new ModernProduct("PROD-100", 24.99);
// The properties are fully accessible right away
echo $product->sku; // Outputs: PROD-100
echo $product->price; // Outputs: 24.99
Important Rules to Remember:
To use constructor property promotion, you must ensure that:
You explicitly provide a visibility modifier (public, private, or protected) inside the parameter list so PHP knows to promote it.
You are inside the __construct() method, as this shortcut does not work on regular methods.