Object-Oriented PHP Programming Tutorial + 10 Code Examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to Use Object-Oriented Programming in PHP the Right Way

Object-Oriented PHP programming is a programming paradigm that uses classes and objects to define the logical structure of an application. OOP is a vast topic with many essential concepts, including inheritance, polymorphism, abstraction, and encapsulation.

This article gives an overview of these important topics and includes some examples to clarify syntax in PHP. If you want to learn more about each of these topics, then follow us in the object-oriented PHP programming series at FuelingPHP.

Table of Contents

What is Object-Oriented PHP Programming?

Object-Oriented Programming (OOP) is a popular programming paradigm that relies on classes and objects as reusable building blocks. Contrary to procedural programming, OOP defines a model for a real-world application, including entities as classes and objects from real-world use cases.

Object-Oriented PHP

Classes and objects are the baselines but these also make use of certain concept that makes object-oriented programming interesting but often difficult for starters. This article sets you on a journey to tackle every idea step-by-step and get the gist of these ideas before diving deep into in-depth articles.

But before we move on to our first topic, let’s understand what is the difference between popular programming paradigms: Procedural vs OOP.

Object-Oriented vs Procedural Programming

A procedural program is a set of instructions that operate on data. Think of it in terms of functions or statements occurring one after another.

While procedural programming could be simple but it has limitations when it comes to modeling a real-life application. Object-oriented has concepts that enable architects and developers to create a logical model of real-life entities. These entities hold all the data and thus interact with other entities in a system, sharing or retrieving this data.

 Object-oriented programming has the following benefits over procedural programming.

  • OOP defines a well-defined structure for an application.
  • Modular and reusable units of code.
  • More data access control, a concept called encapsulation. 
  • It is easier to mock and test a large software using mock objects.

What are Classes Used for in Object-Oriented PHP Programming

Classes and objects are the baselines in object-oriented programming (OOP). Everything is eventually related to these two building blocks.

A class is a template or a blueprint for an object. It defines attributes and behaviors for objects. Inversely, an object is a realization of a class. It is also called an instance of a class. A class can have many objects with the same underlying layout or blueprint.

php classes

Creating Classes with PHP Code Example

A class in PHP is defined with the class keyword followed by a class name.

<?php


//Defines a class
class Square {


   //Attributes (Instance variables)
   public $color;
   private $width;
   protected $height;


   //Constructor
   public function __construct($color, $width, $height) {
       $this->color = $color;
       $this->width = $width;
       $this->height = $height;
   }


   //Behavior (Method)
   public function getArea() {
       return $this->width * $this->height;
   }
}

?>

The example features a set of attributes called instance variables, and a behavior called a method. A method is basically a function, and both terms are interchangeably used, but “methods” is the most term in OOP jargon.

Besides these two, you can see a couple of other things.

  • Access modifiers (public, protected & private).
  • Static and non-static members.
  • Constructor method.
  • $this reference.

These are also important in the context of a class. However, we won’t be diving deep into these because this article is a precursor to more specialized Object-Oriented PHP Programming articles at FuelingPHP.

Creating an object in PHP

An object can be initialized using the new keyword followed by a call to the constructor function.

$square = new Square("Blue", 2, 2);

We can call the public functions of a class on an object as follows.

$square->getArea();

We will have an in-depth article about classes and objects in PHP which will explain the subject in more detail. Stay tuned!

What is Inheritance in Object-Oriented Programming

Inheritance is a popular OOP concept that occurs when a class is derived from another class. Say class B is derived from class A. In OOP terms, we would call this relation inheritance. Class B inherits from class A. In other words, class B is a child, derived, or sub-class of class A. Inversely, class A is a parent or a superclass of class B.

Inheritance is also known as “is-a” relationship. 

But what makes inheritance so special? A person with a rich dad knows well. 😛 In OOP, a class gets all the parent class’s attributes (instance variables) and behaviors (methods). It can add its own attributes and methods and could also redefine some of those behaviors. In OOP words, it is called method overriding.

Object-Oriented PHP

Access modifiers of the class members are worth a topic because private members are not accessible outside a class. Similarly, method overriding is a powerful OOP utility. 

Down the line in Object-Oriented PHP Programming articles, we will discuss all these in depth. 

Inheritance Object-Oriented PHP Code Example

To inherit from a class, use the extends keyword followed by the name of the parent class.

<?php


//Defines a class
class Pet {


   public $name;


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


   public function intro() {
       echo "I'm {$this->name}";
   }


   public function makeSound() {
       echo "No sound";
   }
}


class Dog extends Pet {


   //Override
   public function makeSound() {
       echo "Woof Woof";
   }
}


class Cat extends Pet {


   //Override
   public function makeSound() {
       echo "Meow Meow";
   }
}


$dog = new Dog("Milo");
$dog->intro(); //I'm Milo
$dog->makeSound(); //Woof Woof




$cat = new Cat("Tom");
$cat->intro(); //I'm Tom
$cat->makeSound(); //Meow Meow
?>

OOP in PHP | Composition 

Composition also called “has-a” relationship occurs when one class has references to objects of another class. For instance, if class A has an instance variable that refers to the object of class B, then class A is said to have a (has-a) relationship with class B.

Composition allows a class to call accessible members of another class. In other words, the composition opens up a way to use an API of another class. In software design, composition is usually preferred over inheritance because it helps build more flexible designs.

Want to see composition relation in a practical example? Consider reading strategy pattern in PHP.

Polymorphism in Object-Oriented Programming

Polymorphism (poly – many, morph-forms) is yet another important OOP concept that builds up on the idea of inheritance. When we have a hierarchy of parent-child relationships, then the parent class can hold a reference to all of its child classes. This type of polymorphism is also called dynamic polymorphism.

For example, an Animal is a parent class of the Dog and Cat child classes. We can use a parent class type rather than using Dog or Cat class directly. After all, both are animals at the end of the day.

php polymorphism

But why is it helpful? Why would someone use a parent class if there are child classes already? Polymorphism allows us to write more flexible code. Using more specialized classes often leads to rigid and inflexible systems.

Change is the only constant in a software development lifecycle; no wonder we can add hundreds of animals to the hierarchy. With polymorphism, we don’t have to make changes to the rest of the code because they are all seen by the code as type Animal.

Seeing is believing. Experience the use of polymorphism in various real-world applications featured in our design pattern articles

PHP OOP | Encapsulation & Abstraction

Encapsulation is also essential in object-oriented programming. Encapsulation is bundling data in an object. Access modifiers control access to data members. Data hiding, another important concept, is also related to encapsulation, where private members are out of reach of outside entities.

Abstraction means a layer of simplicity which is a central concept in designing software systems meaning that it offers a simplified outlook for a more complicated system. Software modules that program to these abstractions rather than concrete classes are more flexible and easier to change.

Both abstraction and encapsulation are used when classes and objects come into play. Abstractions are crucial for flexible software design and for creating software for today as well as for tomorrow. Design patterns in PHP heavily rely on abstraction because loosely coupled software always involves abstract layers.

Using Abstract Classes in Object-Oriented Programming

An abstract class in PHP is a class with at least one not implemented method. You cannot use an abstract class directly but must extend it with a child class. The child classes are supposed to provide an implementation for these abstract methods.

An abstract class has some common code and at least one abstract function. They have the benefits of flexibility, code sharing, and usability. 

Consider reading the article about abstract classes in PHP.

Abstract Class PHP Code Example

<?php


//Defines a class
class Pet {


   public $name;


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


   public function intro() {
       echo "I'm {$this->name}";
   }


   //Abstract method
   abstract public function makeSound();
}

class Dog extends Pet {


   //Override
   public function makeSound() {
       echo "Woof Woof";
   }
}


class Cat extends Pet {


   //Override
   public function makeSound() {
       echo "Meow Meow";
   }
}


$dog = new Dog("Milo");
$dog->intro(); //I'm Milo
$dog->makeSound(); //Woof Woof
?>

Using Interfaces in Object-Oriented Programming

Object Oriented Programming (OOP) defines interface as an idea of having a higher level of representation or more precisely an abstraction over more specialized and concrete classes.

Interfaces in object-oriented programming define a type with function declarations having no implementation. Any class which implements an interface has to implement these functions. 

Object-Oriented Programming

Think of it as a contract, a class can implement an interface but if it does so, it is responsible for implementing these functions defined in that interface.

Learn more about PHP interfaces.

Interface PHP Code Example

Defines an interface in PHP with the keyword interface followed by a name. Classes can then implement it using the keyword implements followed by the interface’s name.

The Shape interface defines a method getArea(). Both classes, Circle and Square, implement Shape and provide an implementation.

<?php


interface Shape {


    //Function declaration
    public function getArea();
}

class Circle implements Shape {
   
    //Can define additional properties & methods
    private $PI = 3.14159;
    private $radius;


    function __construct($r) {
        $this->radius = $r;
    }


    //Implements the getArea()
    public function getArea() {
        return ($this->PI * ($this->radius)**2); //Area of a circle is πr^2
    }
}


class Square implements Shape {
   
    //Can define additional properties & methods
    private $length;
    private $width;


    function __construct($l, $w) {
        $this->length = $l;
        $this->width  = $w;
    }


    //Implements the getArea()
    public function getArea() {
        return $this->length * $this->width; //Area of a square is length x width
    }
}

?>

Using Namespaces in Object-Oriented Programming

PHP namespaces are qualifiers that help in organizing groups of related classes. You can repeat a class name in different namespaces thereby avoiding the issue of conflicting names.

Use keyword namespace followed by a name. Note that it has to be the first statement in a PHP file.

<?php
namespace File;


class FileReader {


   public function readFile() {
       echo "Reading a file";
   }
}


class FileWriter {


   public function writeFile() {
       echo "Writing a file";
   }
}
?>

Accessing these classes out of this namespace has to use the fully qualified name as follows.

$fileReader = new File/FileReader();

We can also define nested namespaces as follows.

<?php
namespace File/Image;


class imageRender() {
 echo "Render an image";
}
?>

Learn How to Use Object-Oriented PHP Programming

Object-Oriented PHP is a programming paradigm based on classes and objects. Classes are blueprints for objects that are realizations of these underlying blueprints. But that’s not the only aspect of OOP.

There are other important aspects of OOP, like inheritance which means a sub-class gets attributes and methods of a parent class in addition to their own. Polymorphism is yet another aspect related to the parent-child hierarchy in that a parent class can include a reference and thus represent its child classes. Polymorphism allows us to create more flexible designs by using a generalized instance type.

Composition is also an essential idea in OOP which occurs when a class has reference to one or more objects of a class. Composition is also called “has-a” relationship and it is usually preferred over the inheritance if you want more flexibility in terms of dynamic bindings and associations.

Abstraction and encapsulation are two concepts intertwined with those above, related to data access and a higher view of a complicated system. Abstractions are heavily used in systems that tend to change a lot. These systems use abstractions to make software modules less coupled to the underlying concrete implementations.

Object-oriented programming has benefits, including flexible design with the help of building blocks. Classes and objects are also handy in logically modeling entities of a real-world application.

So, that’s all for now. Hope you have enjoyed the article. Stay tuned at FuelingPHP.

PHP Object-Oriented Programming Learning Path

This article is part of our series on learning Object-oriented programming with PHP. It introduces some concepts, best practices and strategies to help you level up your skills. This is a great intro to growing into a successful programmer.

Continue: Design Patterns in PHP

Want to take your PHP Programming to the next level? Check out our series on using design patterns in PHP. We break down what they are, how to use them, and when you should avoid them. I highly recommend you take a few moments and really focus on this next series.

Click here to check out our design patterns in PHP learning path

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.