Php Immutable objects

Anton Lytvynov
2 min readNov 4, 2019

--

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.

Need professional help in web or mobile development?
Recommendation for planning or estimation of your project?
Feel free to contact me here.

P.S. I really appreciate your like or share 🙏.

--

--

Anton Lytvynov

CEO & Founder of Lytvynov Production, Senior web developer, architect, cryptocurrencies trader, https://lytvynov-production.com