PHP code example of spatie / better-types

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

    

spatie / better-types example snippets


function (FooInterface $foo) {}

$reflectionType = …

$type = new Type($reflectionType);

$type->accepts(new Foo()); // true
$type->accepts('invalid string'); // false

function (?FooInterface $foo, ?BarInterface $bar) {}

$reflectionMethod = …

$method = new Method($reflectionMethod);

$method->accepts(new Foo(), new Bar()); // true
$method->accepts(bar: new Bar() foo: new Foo()); // true
$method->accepts(null, new Bar()); // true
$method->accepts(null, null); // true

$method->accepts('string', 1); // false
$method->accepts(new Foo()); // false, you can't omit values

class Foo
{
    public function acceptsString(string $a) {}
    
    public function acceptsStringToo(string $a) {}
    
    public function acceptsInt(int $a) {}
}

$reflectionClass = …

$handlers = new Handlers($reflectionClass);

$handlers->accepts('string')->all(); // ['acceptsString', 'acceptsStringToo']
$handlers->accepts(1)->first(); // 'acceptsInt'

Attributes::new(AttributesTestClass::class)
    ->instanceOf(AttributesTestAttribute::class)
    ->first();