Php Immutable objects

Anton Lytvynov
Nov 4 · 2 min read

Mutable and immutable classes

A class that contains any methods(not a constructor) that change any of the data in an object of the class is called mutable.

“Mutable” means that something can be changed, and “Immutable” — that something is stable.

That means the mutable objects are those whose data can be changed after the instance is created.

Example of Mutable class

<?php

class
Car
{

/**
*
@var string
*/
private $color;

/**
*
@param string $color
*
*
@return Car
*/
public function setColor(string $color): Car
{
$this->color = $color;
return $this;
}

/**
*
@return string
*/
public function getColor(): string
{
return $this->color;
}
}

Here we can see the method setColor which changes the state.

$car = new Car();
$car->setColor('red');
$car->setColor('green');
$car->setColor('black');

In this case, we change the state of our PHP object after it’s initialization. Actually we can do this as many times as we want.

Example of Immutable class

<?php

class
Car
{
/**
*
@var string
*/
private $color;

/**
* Car constructor.
*
*
@param string $color
*/
public function __construct(string $color)
{
$this->color = $color;
}

/**
*
@return string
*/
public function getColor(): string
{
return $this->color;
}
}

$car = new Car('red');

In this case, our PHP object is immutable. We can not change it after initialization.

Where to use immutable classes/objects?

You should use an immutable object when the changing of your application’s status can be critical.

I hope these two simple examples will explain the main difference.

Thank you for your attention

Thank you for your attention. If you have any questions feel free to contact me. I‘ll be glad to help you.

LinkedIn, Twitter, Google+, https://lytvynov-anton.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade