jumpifbelow/php-typed-array

Library that adds typed array to PHP

2.1.0 2019-06-14 06:44 UTC

This package is auto-updated.

Last update: 2024-04-14 17:49:19 UTC


README

Making PHP able to handle typed array

What it does?

As a developer, you may want to create an array, but to be sure what is inside this. The case looks simple and really familiar in other language, but you cannot create an array with strong type in PHP. This library attempt to solve this nicely and quickly, and moreover really flexible. If the built-in type is not enough, or setting the type as an object is not enough too, you can create your own function. It could be more accurate than only types, like allowing only positive integer.

How to use this?

Simple adds to your composer this line:

composer require jumpifbelow/php-typed-array

and let the magic begin.

How does the code look like?

As this library is really simple, some examples would be far way better than just writing down all the methods individually, without any logic behind this. Here are some working and explained examples.

<?php
use TypedArray\TypedArray;

$t = new TypedArray(TypedArray::TYPE_INT);

$t[] = 5; // it is an int, everyting works great!
$t[] = 'str'; // hell no, it is a string, WrongValueException is thrown

And now, imagine you would like to set some classes:

<?php
use TypedArray\TypedArray;

class CustomClass extends stdClass {}
class InheritedClass extends CustomClass {}

$t = new TypedArray(CustomClass::class);

$t[] = new CustomClass(); // this is the right type
$t[] = new InheritedClass(); // it inherit, so it is still a good value
$t[] = new stdClass(); // the parent class could not work, WrongValueException is thrown

Nice, but yet how you can make it works your own way?

<?php
use TypedArray\TypedArray;

$t = new TypedArray(function ($_item, $_key, $_this): bool {
    return is_int($_item) && $_item >= 0; // check for positive integer
});

$t[] = 4; // a positive integer
$t[] = 0; // null but still accepted
$t[] = -1; // below 0, so the WrongValueException is thrown

If you change your mind, you can either set a new type or a new checker, as shown before. Instead of passing a value to the constructor, just use the setCheckMethod() method.

<?php
use TypedArray\TypedArray;

$t = new TypedArray(TypedArray::TYPE_INT);
$t[] = 1;
$t[] = 2;

// now we are allowing larger set of entries
$t->setCheckMethod(TypedArray::TYPE_NUMERIC);
$t[] = 2.5;