DEV Community

Cover image for Understanding Polymorphism vs. Polymorphic in Programming
Muhamad Sulaiman
Muhamad Sulaiman

Posted on

Understanding Polymorphism vs. Polymorphic in Programming

Introduction

If you've ever dived into Object-Oriented Programming (OOP) or worked with an ORM like Laravel's Eloquent, you've likely come across the terms Polymorphism and Polymorphic Relationship (will use Polymorphic after this). While they sound similar, they refer to two distinct concepts.

Many developers, especially those new to these concepts, often confuse them. In this post, I'll break down what each term means, how they are used, and why understanding the difference is crucial for writing clean and efficient code.


What is Polymorphism?

Polymorphism is a fundamental concept in Object-Oriented Programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables a single interface to be used with different underlying data types, improving code reusability and flexibility.

There are two primary types of polymorphism. Method Overriding and Method Overloading. For the sake of the PHP and this sharing, we focus on the first type only.


Example of Polymorphism in PHP (Method Overriding)

Let's take a real-world example. Assume we have a User system where different types of users (Admin, Customer) have different access levels.

/**
* Main (or Parents) Class
*/
class User {
    public function getRole() {
        return "General User";
    }
}

/**
* Child Class
*/
class Admin extends User {
    public function getRole() {
        return "Administrator - Full Access";
    }
}

/**
* Child Class
*/
class Customer extends User {
    public function getRole() {
        return "Customer - Limited Access";
    }
}

/**
* Instantiate the Class - Object
*/
$users = [new Admin(), new Customer(), new User()];

foreach ($users as $user) {
    echo $user->getRole() . PHP_EOL;
}
Enter fullscreen mode Exit fullscreen mode

Output

Administrator - Full Access
Customer - Limited Access
General User
Enter fullscreen mode Exit fullscreen mode

Here, even though we are calling getRole() on different objects, they return different results based on their respective class implementations. This is the power of polymorphism.

Ok now, I hope you understand about polymorphism. Let's go to other terms, polymorphic.


What is a Polymorphic?

A Polymorphic is a database design pattern used in Object-Relational Mapping (ORM) systems like Laravel's Eloquent. It allows a single model to be associated with multiple other models without needing multiple foreign keys.

For example, let's say we have an Image model that can be associated with both a Post and a User.

Instead of creating separate post_id and user_id columns in the images table, we use a polymorphic relationship with imageable_id and imageable_type columns.

Example of Polymorphic Relationship in Laravel

In your migration file :

Schema::create('images', function (Blueprint $table) {
    $table->id();
    $table->string('url');
    $table->morphs('imageable');
    $table->timestamps();
});
Enter fullscreen mode Exit fullscreen mode

In your Model :

/**
* Image Class
*/
class Image extends Model {
    public function imageable() {
        return $this->morphTo();
    }
}

/**
* Post Class
*/
class Post extends Model {
    public function images() {
        return $this->morphMany(Image::class, 'imageable');
    }
}

/**
* User Class
*/
class User extends Model {
    public function images() {
        return $this->morphMany(Image::class, 'imageable');
    }
}
Enter fullscreen mode Exit fullscreen mode

With this codes, you can do like this when Data Creation :

$post = Post::find(1);
$post->images()->create(['url' => 'post_image.jpg']);

$user = User::find(1);
$user->images()->create(['url' => 'profile_picture.jpg']);
Enter fullscreen mode Exit fullscreen mode

Now, both Post and User models can have associated images without needing separate foreign keys.


Polymorphic Relationships Exist Beyond Laravel

Although Laravel has made Polymorphic relationships popular in the PHP ecosystem, this concept exists in other frameworks and ORMs such as:

  • Django (Python) – Uses Generic Foreign Key

  • Hibernate (Java) – Uses Single Table Inheritance or Join Table Inheritance


Conclusion

Both Polymorphism and Polymorphic are crucial concepts, but they serve different purposes:

  • Polymorphism is an OOP concept that allows multiple classes to share the same interface and behave differently based on their implementation.

  • Polymorphic usually referred as Polymorphic Relationship are a database ORM feature that allows a single model to relate to multiple other models dynamically.


To visualize the difference

  • Polymorphism is like having different types of users (Admin, Customer, Guest) who inherit from a common User class but override methods to behave differently.

  • Polymorphic are like an Image table where a single image can belong to either a Post, a User, or even a Product, without needing multiple foreign keys.


Understanding the difference between these two concepts helps you write cleaner, more maintainable, and scalable code. Whether you’re designing an object-oriented system or a database schema, knowing when and how to use polymorphism can make a huge difference in your project's architecture.

Even there's some Cons. But I don't want to explain it here. Now, it's your job to find the Cons ;)

I'm sure you have implemented the polymorphism in your Laravel project. But Have you used polymorphic relationships in your projects? Let me know in the comments below! πŸš€

Top comments (0)