PHP code example of linna / typed-array

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

    

linna / typed-array example snippets


use Linna\TypedArrayObject\ArrayOfIntegers;
use Linna\TypedArrayObject\ArrayOfClasses;

//correct, only int passed to constructor.
$intArray = new ArrayOfIntegers([1, 2, 3, 4]);

//correct, int assigned
$intArray[] = 5;
//throw InvalidArgumentException, string assigned, int expected.
$intArray[] = 'a';

//correct, int used
$intArray->append(5);
//throw InvalidArgumentException, string used, int expected.
$intArray->append('a');

//throw InvalidArgumentException, mixed array passed to constructor.
$otherIntArray = new ArrayOfIntegers([1, 'a', 3, 4]);

//correct, only Foo class instances passed to constructor.
$fooArray = new ArrayOfClasses(Foo::class, [
    new Foo(),
    new Foo()
]);

//correct, Foo() instance assigned.
$fooArray[] = new Foo();
//throw InvalidArgumentException, Bar() instance assigned.
$fooArray[] = new Bar();

//correct, Foo() instance used.
$fooArray->append(new Foo());
//throw InvalidArgumentException, Bar() instance used, Foo() instance expected.
$fooArray->append(new Bar());

//throw InvalidArgumentException, mixed array of instances passed to constructor.
$otherFooArray = new ArrayOfClasses(Foo::class, [
    new Foo(),
    new Bar()
]);

use Linna\TypedArray;

//slower from 6x to 8x.
$array = new TypedArray('int', [1, 2, 3, 4]);
$array[] = 5;

//other operations, fast as native.
//for example:
$arrayElement = $array[0];
$elements = $array->count();