PHP code example of jasny / typecast

1. Go to this page and download the library: Download jasny/typecast 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 / typecast example snippets


use Jasny\TypeCast;

$typecast = new TypeCast();

$typecast->to('string')->cast(null); // null

$typecast->to('integer')->cast('987'); // 987
$typecast->to(DateTime::class)->cast('2015-01-01'); // new DateTime('2015-01-01)
$typecast->to(FooBar::class)->cast($data); // FooBar::__set_state($data)

// Unable to cast
$typecast->to('float')->cast('red'); // 'red' + triggers a notice
$typecast->to('int')->cast(new stdClass()); // stdClass object + triggers a notice

$typecast = new TypeCast();
$typecast->alias(FooBarInterface::class, FooBar::class);

$typecast->to(FooBarInterface::class)->cast($data); // FooBar::__set_state($data)

$typecast = new TypeCast();

$typecast->failWith(E_USER_WARNING);
$typecast->failWith(TypeError::class);
$typecast->failWith(UnexpectedValueException::class);

$foo = 'red';
$typecast->value($foo)->setName('foo')->to('float');

use Jasny\TypeCast;
use Jasny\TypeCastInterface;

$container = new Container([
  TypeCastInterface::class => function() {
    $typecast = new TypeCast();
    $typecast->alias(FooBarInterface::class, FooBar::class);
    
    return $typecast;
  }
]);

$container->get(TypeCastInterface::class)->value('987')->to('integer');

use Jasny\TypeCast;

$typecast = new TypeCast();
$typecast->desire('integer')->cast('10');

$arrayHandler = $typecast->desire('array'); 
foreach ($items as &$item) {
  $item = $arrayHandler->cast($item);
}

use Jasny\TypeCast;

$multipleHandler = new TypeCast\Handlers\MultipleHandler(new TypeCast\NoTypeGuess()); 
$typecast = new TypeCast(null, ['multiple' => $multipleHandler] + TypeCast::getDefaultHandlers());