PHP code example of jasny / immutable

1. Go to this page and download the library: Download jasny/immutable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jasny / immutable example snippets


class ImmutableFoo
{
    use Jasny\Immutable\NoDynamicProperties;
}

class ImmutableFoo
{
    public function withSomething(string $newValue)
    {
        if ($this->something === $newValue) {
            return $this;
        }

        $clone = clone $this;
        $clone->something = $newValue;

        return $clone;
    }
}

class ImmutableFoo
{
    use Jasny\Immutable\With;
    
    protected $something;

    public function withSomething(string $value): self
    {
        return $this->withProperty('something', $value);
    }

    public function withoutSomething(): self
    {
        return $this->withoutProperty('something');
    }
}

class ImmutableFoo
{
    use Jasny\Immutable\With;

    protected array $colors = [];

    public function withColor(string $color, int $level): self
    {
        return $this->withPropertyKey('colors', $color, $level);
    }

    public function withoutColor(string $color): self
    {
        return $this->withoutPropertyKey('colors', $color);
    }
}

class ImmutableFoo
{
    use Jasny\Immutable\With;

    protected array $services = [];

    public function withAddedService($service): self
    {
        return $this->withPropertyItem('services', $service, true /* unique */);
    }

    public function withoutService($service): self
    {
        return $this->withoutPropertyItem('services', $service);
    }
}