PHP code example of selfphp / php-typecheck

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

    

selfphp / php-typecheck example snippets


use Selfphp\PhpTypeCheck\TypeChecker;

TypeChecker::assertArrayOfType([1, 2, 3], 'int');       // ✅ OK
TypeChecker::assertArrayOfType(['a', 'b'], 'string');   // ✅ OK

TypeChecker::assertArrayOfType([new User(), new User()], User::class); // ✅ OK

$data = [[1, 2], [3, 4]];
TypeChecker::assertArrayOfType($data, 'int', true); // ✅ OK

TypeChecker::assertArrayOfType([1, 'two', 3], 'int');
// ❌ Throws TypeCheckException: Element at [1] is of type string, expected int

if (!TypeChecker::checkArrayOfType([1, 'two'], 'int')) {
    echo "Invalid array values!";
}

$data = ['email' => '[email protected]'];
$schema = ['email' => 'string', 'phone?' => 'string'];

if (!TypeChecker::checkStructure($data, $schema)) {
    echo "Invalid structure!";
}

TypeChecker::assertStructure(
    ['name' => 'Alice', 'age' => 30],
    ['name' => 'string', 'age' => 'int']
);

// with nested structures and optional keys
TypeChecker::assertStructure(
    ['profile' => ['city' => 'Berlin'], 'email' => '[email protected]'],
    ['profile' => ['city' => 'string'], 'email?' => 'string']
);

try {
    TypeChecker::assertArrayOfType([1, 'x'], 'int');
} catch (TypeCheckException $e) {
    echo json_encode($e->toArray(), JSON_PRETTY_PRINT);
}

TypeChecker::describeType(42);                         // int
TypeChecker::describeType(['a', 'b']);                 // array<string>
TypeChecker::describeType([1, 'x']);                   // array<int|string>
TypeChecker::describeType([new User(), new User()]);  // array<User>
bash
composer