PHP code example of azjezz / typed

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

    

azjezz / typed example snippets


 declare(strict_types=1);

use Typed as t;

$name = &t\string('saif');
$age = &t\int(19);

try {

  $name = 'azjezz'; // works
  $name = 15; // fails
  $age = null; // fails

} catch(TypeError $error) {
   
} finally {
    t\clean();
}

 declare(strict_types=1);

use Typed as t;
    
$name = &t\string('azjezz', 'data');
$age = &t\int(19, 'data');

t\delete($name, 'data');

/**
 * the reference to the `$name` variable has been deleted.
 * therefor we can assign any type to the variable `$name` now. 
 */
$name = []; // works

 declare(strict_types=1);

use Typed as t;
use function Typed\c;

/**
 * all assigned variables inside the callable will be destroyed after execution. 
 */
c(function(): void {
    $name = &t\string('saif eddin');
    $age = &t\int(5);
    $arr = &t\arr([
        'age' => $age,
        'name' => $name    
    ]);
});


 declare(strict_types=1);

use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use function Typed\c;

class TypedMiddleware implements MiddlewareInterface 
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = null;
        c(function() use($request, &$response, $handler) {
            /**
             * if any typed variable is created in the handler, it would be deleted after execution.
             */
            $response = $handler->handle($request);
        });
        return $response;
    }
}