PHP code example of serafim / properties

1. Go to this page and download the library: Download serafim/properties 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/ */

    

serafim / properties example snippets


class MyClass
{
    protected $a = 23;

    public function __get($field)
    {
        return $this->$field;
    }
}

$dto = new MyClass();
echo $dto->a; // 23
$dto->a = 42; // Cannot access protected property MyClass::$a

/**
 * @property-read int $a
 */
class MyClass
{
    // ...

$dto = new MyClass();
echo isset($dto->a); // false

/**
 * @property $a
 */
class MyClass
{
    use Serafim\Properties\Properties;
    
    protected $a = 23;
}

$dto = new MyClass();
$dto->a;      // 23
$dto->a = 42; // Ok
$dto->a;      // 42

/**
 * @property-read $a
 */
class MyClass
{
    use Serafim\Properties\Properties;
    
    protected $a = 23;
}

$dto = new MyClass();
$dto->a;      // 23
$dto->a = 42; // Error: Property MyClass::$a is readonly

/**
 * @property-write $a
 */
class MyClass
{
    use Serafim\Properties\Properties;
    
    protected $a = 23;
}

$dto = new MyClass();
$dto->a = 42; // 42
$dto->a;      // Error: Property MyClass::$a is writeonly

/**
 * @property-read int $a
 */
class MyClass
{
    use Serafim\Properties\Properties;
    
    protected $a = 23;

    protected function getA() 
    {
        return $this->a + 19;
    }
}

$dto = new MyClass();
echo $dto->a; // 42 (because 23 + 19 = 42)
$dto->a = 42; // Error: Property is read-only (@property-read doc declaration)

/**
 * @property-write string $anotherProperty
 */
class Some 
{
   // ... 
   protected $anotherProperty = 'some';
   
    /**
     * @param string $newVal
     */
   public function setAnotherProperty($newVal) 
   {
       // Just example
       if (mb_strlen($newVal) > 4) {
           throw new InvalidArgumentException('...');
       }
       
       $this->anotherProperty = $newVal;
   }
}

/**
 * @property int|null $a
 */
class Some
{
    use Serafim\Properties\Properties;
    
    protected $a; 
}

//

$some = new Some;
$some->a = 23; // Ok
$some->a = null; // Ok
$some->a = 'string'; // Error: "TypeError: Value for property Some::$a must be of the type int|null, string given"

$driver = new Psr16CacheDriver(); // Your PSR16 cache driver implementation 

$properties = Serafim\Properties\Bootstrap::getInstance();
$properties->setCacheDriver($driver);