PHP code example of moebrowne / erased-generics

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

    

moebrowne / erased-generics example snippets


// Function parameters
function foo(array<Widget> $items) {}
function foo(array<string, int> $map) {}
function foo(Map<string, Widget> $map) {}

// Return types
function getWidgets(): array<Widget> {}
function getMap(): Map<string, Widget> {}
function getData(): array<string, int> {}

class Foo<TModel> {
    public TModel $item;

    public function foo(TModel $value): TModel {}
}

// Class instantiation
new Thing<Widget>();
new Pair<string, int>();

// Class properties
class Foo {
    public array<Widget> $widgets;
}

// Class methods
class Foo {
    public function getWidgets(): array<Widget> {}
    private function getMap(): Map<string, int> {}
    protected static function getData(): Collection<Widget> {}
}

// Constructor promotion
class Foo {
    public function __construct(
        public Collection<Widget> $widgets,
        private array<int> $ids,
    ) {}
}

// Closure parameters
$process = function (array<Widget> $items) {};
$map = function (Map<string, int> $data) {};
$filter = fn (Collection<Widget> $widgets) => count($widgets);

// Closure return types
$closure = function(): array<Widget> {};
$fn = fn(): array<string, int> => [];

function foo(array<Map<string, Widget>> $data) {}
function getNestedData(): array<Map<string, Widget>> {}

// Union types with generics
function process(array<Widget>|null $items) {}
function handle(Collection<Widget>|array<Widget> $data) {}
function fetch(): array<string, int>|false {}

// Union types inside generic brackets
function process(Collection<Widget|string> $data) {}
function transform(array<Widget|string|int> $items) {}

// Union types in classes
class Container {
    public array<Widget>|null $widgets;
    public Collection<Widget|Thingy> $items;

    public function __construct(
        public array<Widget>|null $data,
    ) {}

    public function find(): array<Widget>|null {}
}

function foo(array<\App\Models\Widget> $items) {}
new Collection<\App\Models\Widget>();
function getModels(): array<\App\Models\Widget> {}

function foo(array<?Widget> $items) {}
function foo(?array<Widget> $items) {}

php -d extension=/path/to/erased-generics/modules/erased_generics.so -f file.php