PHP code example of jclaveau / php-immutable-trait

1. Go to this page and download the library: Download jclaveau/php-immutable-trait 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/ */

    

jclaveau / php-immutable-trait example snippets


class ImmutableObject
{
    use Immutable;
    // use SwitchableMutability; // This traits provides becomesMutable() and becomesImmutable()

    protected $property;

    public function setProperty($value)
    {
        // Just add these lines at the really beginning of methods supporting
        // immutability (setters mostly)
        if ($this->callOnCloneIfImmutable($result))
            return $result;

        // $this is now the new instance if it's immutable
        $this->property = $value;
        return $this;
    }

    public function getProperty()
    {
        return $this->property;
    }
}


$instance = new ImmutableObject;
$instance2 = $instance->setProperty('new value');

var_dump( $instance->getProperty() ); => null
var_dump( $instance2->getProperty() ); => 'new value'