Class and Object in PHP with Example

Mohasin Hossain
4 min readSep 29, 2023

--

Today we going to explore what is Class and Object in PHP and how to use it.

Few things we need to know about Class.

Think of a class as a blueprint or template that defines the overall structure and behavior for some concept in your codebase.
Class is like a blueprint that defines the structure for objects, which are concrete instances of that class.

Let’s see some basic code example of Class

<?php
// Define a class called "Person"
class Person {
// Properties (variables)
public $name;
public $age;

// Constructor method
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}

// Method to display information about the person
public function displayInfo() {
echo "Name: " . $this->name . "<br>";
echo "Age: " . $this->age . " years old<br>";
}
}

// Create an instance of the Person class
$person1 = new Person("John", 30);

// Access the properties and call methods
$person1->displayInfo();

// Create another instance of the Person class
$person2 = new Person("Alice", 25);
$person2->displayInfo();
?>

Let’s see some real life code example

<?php
class Product {
// Properties
private $productId;
private $name;
private $price;
private $description;
private $quantityInStock;

// Constructor
public function __construct($productId, $name, $price, $description, $quantityInStock) {
$this->productId = $productId;
$this->name = $name;
$this->price = $price;
$this->description = $description;
$this->quantityInStock = $quantityInStock;
}

// Methods

// Getters and Setters
public function getProductId() {
return $this->productId;
}

public function getName() {
return $this->name;
}

public function setName($name) {
$this->name = $name;
}

public function getPrice() {
return $this->price;
}

public function setPrice($price) {
$this->price = $price;
}

public function getDescription() {
return $this->description;
}

public function setDescription($description) {
$this->description = $description;
}

public function getQuantityInStock() {
return $this->quantityInStock;
}

public function setQuantityInStock($quantityInStock) {
$this->quantityInStock = $quantityInStock;
}

// Method to calculate the total value of the product inventory
public function calculateInventoryValue() {
return $this->price * $this->quantityInStock;
}

// Method to display product information
public function displayProductInfo() {
echo "Product ID: " . $this->productId . "<br>";
echo "Name: " . $this->name . "<br>";
echo "Price: $" . $this->price . "<br>";
echo "Description: " . $this->description . "<br>";
echo "Quantity in Stock: " . $this->quantityInStock . "<br>";
echo "Total Inventory Value: $" . $this->calculateInventoryValue() . "<br>";
}
}

// Create an instance of the Product class
$product1 = new Product(1, "Smartphone", 499.99, "High-end smartphone with advanced features.", 100);

// Display product information
$product1->displayProductInfo();

// Update product information
$product1->setName("New Smartphone Model");
$product1->setPrice(599.99);
$product1->setQuantityInStock(150);

// Display updated product information
$product1->displayProductInfo();
?>

Now let’s talk about object

If a class is the blueprint, then an object is an instance (or implementation) of that blueprint.

In the above example person1 is the object of Person class. and product1 is the object Product class.

Let’s wrap up the class and object concept

Class:

  • A class is a blueprint or template for creating objects in PHP.
  • It defines the properties (variables) and methods (functions) that the objects created from the class will have.
  • Classes provide a way to encapsulate and organize code into reusable units.

Object:

  • An object is an instance of a class, created using the new keyword.
  • Objects have their own unique set of properties and can perform actions defined by the class’s methods.
  • They allow you to work with specific instances of a class and maintain separate states.

Properties:

  • Properties are variables defined within a class.
  • They represent the characteristics or attributes of objects created from the class.
  • Properties can have visibility modifiers like public, private, or protected, which control their access from outside the class.

Methods:

  • Methods are functions defined within a class.
  • They define the behavior or actions that objects created from the class can perform.
  • Methods can also have visibility modifiers like public, private, or protected.

Constructor:

  • A constructor is a special method that is called automatically when an object is created from a class.
  • It is used to initialize the object’s properties or perform other setup tasks.
  • In PHP, the constructor method is named __construct().

Access Modifiers:

  • PHP provides three access modifiers for class members: public, private, and protected.
  • public: Members are accessible from outside the class.
  • private: Members are only accessible from within the class itself.
  • protected: Members are accessible from within the class and its subclasses.

Encapsulation:

  • Encapsulation is the concept of bundling data (properties) and methods (functions) that operate on that data within a single unit (a class).
  • It allows you to control access to the internal state of an object and hide implementation details.

Inheritance:

  • Inheritance allows you to create a new class (subclass or child class) based on an existing class (superclass or parent class).
  • The child class inherits the properties and methods of the parent class.
  • It allows for code reuse and the creation of more specialized classes.

Object Instantiation:

  • Objects are created by instantiating a class using the new keyword, followed by the class name and parentheses (if the constructor requires arguments).

In summary, classes and objects in PHP provide a way to structure and organize code, allowing for the creation of reusable and modular software components. They are essential for object-oriented programming in PHP.

For more details of OOP (Object Ordinated Programming) , you may have a look at the link given below. Feel free to leave a comment if you have any feedback or questions.

https://github.com/mohasin-dev/Object-Oriented-Programming-in-PHP

Bonus: You must love my most read article : How To Use Single Responsibility Principle in PHP/Laravel
And most GitHub star repo:
https://github.com/mohasinhossain/SOLID-Principles-in-PHP

--

--

Mohasin Hossain

Senior Software Engineer | Mentor @ADPList | Backend focused | PHP, JavaScript, Laravel, Vue.js, Nuxt.js, MySQL, TDD, CI/CD, Docker, Linux