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

Senior web developer, architect, cryptocurrencies trader, https://lytvynov-anton.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store